79272

why xml file does not aligned properly after append the string in beginning and end of the file usin

I have added the string in beginning and end of the XML File.but the alignment is not proper after getting the result.

My XML File:

import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import com.google.common.io.Resources; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.nio.charset.Charset; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class ModifyXMLFile { public static void main(String args[]) { try { // Point the file directory path here String directory = "C:\\Users\\n444479\\Desktop\\SA"; int test = new File("C:\\Users\\n444479\\Desktop\\SA").listFiles().length; File[] files = new File(directory).listFiles(); // Loop the file to run all the XML files for (int j = 0; j < test; j++) { System.out.println(files[j]); String filepathext = files[j].toString(); DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepathext); /* // XML file update starts here // 1.Add the attribute element with value between the two XML // Child elements NodeList nodes = doc.getElementsByTagName("dummySegmentOne"); Text a = doc.createTextNode("value"); Element p = doc.createElement("newNode"); p.appendChild(a); nodes.item(0).getParentNode().insertBefore(p, nodes.item(0)); // 2.Add the attribute element without value between the two XML // Child elements NodeList nodesa = doc.getElementsByTagName("customerLevelRegDocs"); Element q = doc.createElement("dummySegmentOne"); nodesa.item(0).getParentNode().insertBefore(q, nodesa.item(0)); // 3.Rename the element in parent and child both using the JAXP // Parser */ // XSLT File: String xsltResource = "C:\\Users\\n444479\\Desktop\\AB\\test.xml"; StringWriter xmlResultResource = new StringWriter(); Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer( new StreamSource(new File(xsltResource))); xmlTransformer.transform(new StreamSource(new File(filepathext)),new StreamResult(xmlResultResource)); // XML file update end here // write the content into XML file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new String(filepathext)); transformer.transform(source, result); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Successful output once get it "Done" String output = xmlResultResource.getBuffer().toString(); // Writing the transformed XML to a file FileWriter fileWriter = new FileWriter(filepathext); fileWriter.write(output); fileWriter.close(); System.out.println("Done"); } } // Exception handling catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } } }

Once the program executed the string get appended properly but the XML File alignment changed.

The output i am getting as below

<?xml version="1.0" encoding="UTF-8"?>{% from lxml import etree %}{% from StringIO import StringIO %}{% set tree = parse_xml(request_text) %}{% set namespaces = {'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 'wbs': 'http://xml.ama.com/ws/2009/01/WBS_Session-2.0.xsd'}%}<soap:Envelope xmlns:xalan="http://xml.apache.org/xalan" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><Session><SessionId>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SessionId', namespaces=namespaces)[0].text}}</SessionId><SequenceNumber>{{int(tree.xpath('//soapenv:Header/wbs:Session/wbs:SequenceNumber', namespaces=namespaces)[0].text)+1}}</SequenceNumber><SecurityToken>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SecurityToken', namespaces=namespaces)[0].text}}</SecurityToken></Session></soap:Header><soap:Body><reRoot><reNode> world</reNode></reRoot></soap:Body></soap:Envelope>

why the file not getting appeneded

Answer1:

The reason is that DataInputStream.readLine discards the newline character. So, you'll have to append it yourself.

Moreover: Take in account that the resulting XML is incorrect, because the original XML header turns out to be included in one node. The header (if present) must stay always before the root node.

To properly transform your input XML to a SOAP, I recommend you two alternatives:

    <li>Either transform it through an <strong>XSL</strong> stylesheet.</li> <li>Or either build the resulting XML with <strong>DOM</strong> and include the source XML as one child node. Then, when serializing the whole document, you may specify indentation parameters.</li> </ul>

    <strong>Update</strong>

    I suggest you this XSL:

    <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8"/> <xsl:strip-space elements="*"/> <xsl:template match="/">{% from lxml import etree %}{% from StringIO import StringIO %}{% set tree = parse_xml(request_text) %}{% set namespaces = {'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 'wbs': 'http://xml.ama.com/ws/2009/01/WBS_Session-2.0.xsd'}%}<soap:Envelope xmlns:xalan="http://xml.apache.org/xalan" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <Session> <SessionId>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SessionId', namespaces=namespaces)[0].text}}</SessionId> <SequenceNumber>{{int(tree.xpath('//soapenv:Header/wbs:Session/wbs:SequenceNumber', namespaces=namespaces)[0].text)+1}}</SequenceNumber> <SecurityToken>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SecurityToken', namespaces=namespaces)[0].text}}</SecurityToken> </Session> </soap:Header> <soap:Body><xsl:copy-of select="."/> </soap:Body> </soap:Envelope> </xsl:template> </xsl:stylesheet>

    In other words: It creates a SOAP message with a fixed format, and sets the input xml as the contents of the <soap:Body> node.

    And the transformation code:

    private static void transform(org.w3c.dom.Document doc, java.io.InputStream inputXsl, java.io.OutputStream out) throws java.io.IOException, javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException { javax.xml.transform.Templates templates=javax.xml.transform.TransformerFactory.newInstance().newTemplates(new javax.xml.transform.stream.StreamSource(inputXsl)); javax.xml.transform.Transformer transformer=templates.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); javax.xml.transform.Result result=new javax.xml.transform.stream.StreamResult(out); javax.xml.transform.Source source=new javax.xml.transform.dom.DOMSource(doc); if (doc.getInputEncoding() != null) { transformer.setOutputProperty("encoding", doc.getInputEncoding()); } transformer.transform(source, result); }

    The whole result is re-indented by means of two causes:

      <li>The xsl:strip-space in the XSL.</li> <li>The indent and indent-amount properties in the transformation.</li> </ul>

      Answer2:

      The below XSL Stylesheet will be formatting the xml properly

      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:strip-space elements="*"/> <!-- identity transform --> <xsl:template match="/"> {% from lxml import etree %}{% from StringIO import StringIO %}{% set tree = parse_xml(request_text) %}{% set namespaces = {'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 'wbs': 'http://xml.ama.com/ws/2009/01/WBS_Session-2.0.xsd'}%} <soap:Envelope xmlns:xalan="http://xml.apache.org/xalan" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <Session> <SessionId>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SessionId', namespaces=namespaces)[0].text}}</SessionId> <SequenceNumber>{{int(tree.xpath('//soapenv:Header/wbs:Session/wbs:SequenceNumber', namespaces=namespaces)[0].text)+1}}</SequenceNumber> <SecurityToken>{{tree.xpath('//soapenv:Header/wbs:Session/wbs:SecurityToken', namespaces=namespaces)[0].text}}</SecurityToken> </Session> </soap:Header> <soap:Body><xsl:copy-of select="."/> </soap:Body> </soap:Envelope> </xsl:template> </xsl:stylesheet>

      @Little Santi thanks for helping me and getting understand things.

Recommend

  • Save array as xml
  • JS: How to concatenate variables inside appendChild()?
  • Preserve charset attribute of meta tag in HTML Blob?
  • elt.lang = 'fr' not working
  • JS get value of generated textnode
  • How do I make new messages appear on left/right depending on who sent them? (No Float)
  • Replace last character while user typing in contenteditable div
  • Getting different value with placeholder over CPU/GPU
  • Python pickle not one-to-one: different pickles give same object
  • Combining two different ActiveRecord collections into one
  • Automatically associate new Sonar project with custom quality profile and quality gate
  • Tamper-proof configuration files in .NET?
  • C: Incompatible pointer type initializing
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • htaccess add www if not subdomain, if subdomain remove www
  • How to attach a node.js readable stream to a Sendgrid email?
  • JSON response opens as a file, but I can't access it with JavaScript
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Python CGI os.system causing malformed header
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Master page gives error
  • HTML download movie download link
  • Accessing IRQ description array within a module and displaying action names
  • JSON with duplicate key names losing information when parsed
  • Weird JavaScript statement, what does it mean?
  • Jquery - Jquery Wysiwyg return html as a string
  • Confusion with PayPal's monthly billing cycle
  • retrieve vertices with no linked edge in arangodb
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Angular 2 constructor injection vs direct access
  • Understanding cpu registers
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • Add sale price programmatically to product variations
  • Can't mass-assign protected attributes when import data from csv file
  • sending mail using smtp is too slow
  • Django query for large number of relationships
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS