A class to format an XML string into indented xml code

I am looking for a class or a piece of code to format an XML string into indented xml code
for example: an XML string as follows
<servlet><servlet-name>Login</servlet-name>servlet-class>ucs.merch.client.system.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>Login</servlet-name>
to format into :
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>ucs.merch.client.system.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
e-mail : [email protected]

Xerces has a class called OutputFormat
If you have your XML document in memory, you can format it using the method setIndenting(true) on the OutputFormat class. The following is an example:
assuming xmlDoc is our document and fileName is the name of the file we wish to write to:
OutputFormat format = new OutputFormat(xmlDoc);
// setup output file name
PrintWriter printwriter = new PrintWriter(new FileWriter(fileName, false));
// construct an XMLSerializer for writing the document
XMLSerializer serializer = new XMLSerializer( printwriter, format );
// Ensure output is indented correctly...
format.setIndenting(true);
// set serializer as a DOM Serializer
serializer.asDOMSerializer();
// serialize the document
serializer.serialize(xmlDoc);
hope this helps!
Rob.

Similar Messages

  • Convert XML string into an abap format date and time

    Hi,
    Does anyone know of a method or a function module in ABAP which converts XML string into an abap format date and time.
    Here is a part of the xml that I want to convert.
    <ns2:EventDateTime>2009-07-02T10:13:45+10:00</ns2:EventDateTime>
    <ns2:EventMessageTransmissionDateTime>2009-07-02T10:13:45.987+10:00</ns2:EventMessageTransmissionDateTime>
    Currently EventDateTime and EventMessageTransmissionDateTime are type XSDDATETIME_Z and these are converted to proper dates and times. We will be changing these fields to a STRING instead of XSDDATETIME_Z. The reason for this is to make the field more versatile. The customer would be receiving dates with Zulu (2009-09-23T12:00:00Z), with offsets (2009-09-23T12:00:00+10:00/-10:00) and just local timestamp (2009-09-23T12:00:00). With this, we need to make the date fields as string
    to be able to accept the various date formats (esp. the local timestamp).
    I am looking for a standard function module or method that will convert the xml string to a proper date and time abap format.
    Would appreciate anyone's help!
    Thanks.
    Edited by: eunice ocson on Jul 13, 2009 1:49 AM
    Edited by: eunice ocson on Jul 13, 2009 1:50 AM
    Edited by: eunice ocson on Jul 13, 2009 1:51 AM
    Edited by: eunice ocson on Jul 13, 2009 1:51 AM

    Hi Eunice
    Use the FM 'SMUM_XML_PARSE'
    for more info
    [Convert XML string to ABAP|XML String to ABAP or GUI]
    hope it helps you.
    Thanks!!

  • How to Parse a string into an XML DOM ?

    Hi,
    I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?

    Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
    - Saish
    public final class DomParser extends Object {
         // Class Variables //
         private static final DocumentBuilder builder;
         private static final String JAXP_SCHEMA_LANGUAGE =
             "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         /** W3C schema definitions */
         private static final String W3C_XML_SCHEMA =
             "http://www.w3.org/2001/XMLSchema";
         // Constructors //
         static {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   builder = factory.newDocumentBuilder();
                   builder.setErrorHandler(new ErrorHandler() {
                       public void warning(SAXParseException e) throws SAXException {
                           System.err.println("[warning] "+e.getMessage());
                       public void error(SAXParseException e) throws SAXException {
                           System.err.println("[error] "+e.getMessage());
                       public void fatalError(SAXParseException e) throws SAXException {
                           System.err.println("[fatal error] "+e.getMessage());
                           throw new XmlParsingError("Fatal validation error", e);
              catch (ParserConfigurationException fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
              catch (FactoryConfigurationError fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
         private DomParser() {
              super();
         // Public Methods //
         public static final Document newDocument() {
              return builder.newDocument();
         public static final Document parseDocument(final InputStream in) {
              try {
                   return builder.parse(in);
              catch (SAXException e) {
                   throw new XmlParsingError("SAX exception during parsing.  Document is not well-formed or contains " +
                        "illegal characters", e);
              catch (IOException e) {
                   throw new XmlParsingError("Encountered I/O exception during parsing", e);
    }- Saish

  • Convert XML string into XML

    Hi All,
    Can you please let me know for any sample code in xslt/java mapping for converting XML string into XML. We use SAP Pi 7.0
    My XML string starts like this
    <?xml version="1.0" encoding="UTF-8" ?> 
    - <ns0:MT_ReceiverFileStructure <namespace>"><Output><?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<xsl>"?><Tarih_Date Tarih="11.09.2014" Date="09/11/2014>
       Thanks,
       Pavithra

    Thanks Praveen. It worked.
    However, the xml i have is an extract from a exchange rate URL and it has the reference to a xsl in it as below
    <?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<ABC.xsl>"?>.
    So there is an error in sxmb_moni. Is it possible to remove this.

  • How to get an xml string into a Document w/o escaping mark-up characters?

    Hi,
    I am using one of the latest xerces using Java. I am pretty sure I am using xerces-2.
    I have an existing Document and I am trying to add more content to it. The new content itself is xml string. I am trying to insert this xml string into the document using document.createTextNode. I am able to insert, but somewhere it is escaping the mark-up characters (<,>,etc). When I convert the document into String, I can see, for example, <userData> instead of <userData>.
    There is an alternative option to accomplish this by creating a new document with this xml string, get the root element, import this element into my document. Execution time for this procedure is very high - means, this is very bad in terms of time-wise performance.
    Can any help on how to accomplish this (bringing an xml string into a document without escaping mark-up characters) in time-efficient way.

    So you want to treat the contents of the string as XML rather than as text? Then you have to parse it.
    Or if your reason for asking is just that you don't like the look of escaped text, then use a CDATA section to contain the text.

  • Does anyone can help me to import XML string into a ORACLE database

    Hi guys!
    i have some problem that my friend wants me to convert XML string to Oracle relational database which means.
    let's say, there is a table that a row has XML string.
    so table has XML string with varchar type.
    what my friend want me to do is, the string needs to be solved as a relational database.
    like
    A table has 'ID', 'data', 'result' rows
    and Data column has XML string like <?xml version...............>
    then wants to convert that data column's XML data into TABLE B with structure normally XML has.
    i'm so confused and have no idea at all.. also i couldn't find any solution related to my stuff..
    if someone knows how to solve the problem, just let us know
    thx

    The database is 10.2.0
    What sort of example do u want me to give you..
    i thought i give all information on the post..
    i will explain it
    let's say there are 3 columns ID,Name,Code
    Id = normal integer
    Name= varchar
    Code= varchar
    and i need to conver that XML in the Code column into relational databases
    the code column has normal XML code which is starting from <?xml version.... and so on
    so does it explain?
    please help me!

  • Convert XML string into DOM

    Hi all,
    I have a question here regarding converting XML string into a DOM document.
    How can I do this in Java?
    The Document.Parse() methods do not have one that takes in String as its parameter.
    I'm not sure what is the best way to do this in Java.
    Any help is greatly appreciated.
    Thank you in advance.
    regards,
    Sean

    Convert XML String to Document with StringReader.
    String xmlString;
    DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
       Document         document = builder.parse(new InputSource(new StringReader(xmlString)));

  • REG: WRITE XML STRING INTO XML FILE

    Hi All, I have a XML FILE on PC. I get a xml string from my server.
    My Task: I want to append the xml string coming from the server into the existing xml file at a particular Node. Given below is my code :
    String xmlString = baos.toString();
                      DocumentBuilder db4XMLString = docBuilderFactory.newDocumentBuilder();
                      InputSource inStream = new InputSource();
                      inStream.setCharacterStream(new StringReader(xmlString));
                      Document doc4XMLString = db4XMLString.parse(inStream);
                      Node root4XMLString = doc4XMLString.getElementsByTagName("epg").item(0);
                      doc.appendChild(doc.importNode(root4XMLString, true));
                      File file = new File(Constant.XMLFILEPATH);
                      Result result = new StreamResult(file.toURI().getPath());
                      Source source = new DOMSource(doc);
                      Transformer xformer = TransformerFactory.newInstance().newTransformer();
                      xformer.transform(source, result);But, wen i run my application I get following exception:
    The markup in the document following the root element must be well-formed.
    org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    Is that my XML string is not well formed. Is it so then please let me how to convert my xml string into well formed XML data.
    Please help me out.
    Thanking You.

    There are many reasons why xmlString could be not well formed. There is no magic recipe for making it well formed: just look at it and see why it is not parseable.
    Note that this line:
    String xmlString = baos.toString();can be problematic if you have non ASCII-7 characters in your XML document. baos could then contain a byte representation of these characters in one particular encoding, but, since you use the .toString() method that relies on the default encoding of your system, you can end up with a mismatch and garbage in your XML.

  • Xml data into non-xml database.. solution anyone?

    Hi,
    My current project requires me to store the client's data on our servers. We're using Oracle9i. Daily, I will download the client's data for that day and load it into our database. My problem is that the data file is not a flat file so I can't use sql*loader to load the data. Instead, the data file is an xml file. What is the best way to load xml data into a non-xml database? Are there any tools similar to sql*Loader that will load xml data into non-xml database? Is it the best solution for the client to give me an XML dump of their data to load into our database, or should I request a flat file? My last resort would be to write some sort of a script to parse the xml data into a flat file, and then run it through sql*loader. Is this the best solution? One thing to note is that these files could be very large.
    Thanks in advance.
    -PV

    I assume that just putting the XML file into an
    extremely large VARCHAR field is not what you want.
    Instead, you want to extract data elements from the
    XML and write them to columns in a table in your
    database. Right?Yes. Your assumption is correct.
    It sounds like you already have a script that loads a
    flat file into your database. In that case I would
    write an XSL transformation that converts the client's
    XML into a correctly-formatted flat file.Thank you. I'll look into that. Other suggestions are welcome.

  • How can I parse an XML string, (not an XML file)?

    Hi,
    I am using Xerces2 Java Parser 2.4.0,
    I wanta parse an XML string, not an XML file, but
    in the Parser class there is only following methods:
    parse(InputSource source)
    parse(java.lang.String systemId)
    thanks

    hi
      InputSource is = new InputSource(new ByteArrayInputStream(xmlSrc.getBytes()));
      HTH
    vasanth-ct

  • Load XML file into oracle xml buffer

    Hi guys,
    I'm a starter in Oracle XML Development, I wander how I can load a xml file into oracle xml buffer(xmlctx* document) through programming with c++ in visual studio.
    When I use orastream structure, it compiled failed.
    Thank you very much!
    Edited by: pomelo on 2010-11-15 下午5:39

    try this
    LOAD DATA
    INFILE '/home/oraread/'
    INTO TABLE xmlloadtable
    (id,
    file_name          filler,
    data_xml          lobfile(file_name) terminated by eof
    )you can add the file_name field as a column to your table between the id and xml column and remove the filler word in the .ldr file if you need to keep the name of the file

  • Parsing an xml string into id-value pair format

    Hi,
    I am new in oracle BPEL.
    My requirement is that I need to parse an xml string containing tag name and coressponding value into an 'id -value' pair.
    For example-
    The input xml format is -
    <employee>
    <empid>12345</empid>
    <name>xyz</name>
    <city>London</city>
    </employee>
    The required xml format is-
    <employee>
    <item id="empid" value="12345"/>
    <item id="name" value="xyz"/>
    <item id="city" value="London"/>
    </employee>
    Please let me know if there is a work-around for this.
    Thanks

    Something like this (have not tested):
    <xsl:for-each select="//employee">
    <employee>
    <xsl:for-each select="./*">
    <item>
    <xsl:attribute name="id">
    <xsl:value-of select="name()"/>
    </xsl:attribute>
    <xsl:attribute name="value">
    <xsl:value-of select="text()"/>
    </xsl:attribute>
    </item>
    </xsl:for-each>
    </employee>
    </xsl:for-each>

  • Help: How to parse XML string into Node Context

    Hi Experts,
    I am trying to work with a web dynpro for java application which calls a Web Service. I can call the web service successfully, however I have a problem on interpreting the response result into table. The response result is in (XML) string format, like this:
    I followed this , but it resulted to an error:
    com.sap.engine.lib.xml.parser.NestedSAXParserException: Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)(:main:, row=158, col=59) -> com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)
    do anyone of you had a similar experience and were able to resolve it, please post it here. it will be highly appreciated. thanks in advance.

    Try this :
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new org.xml.sax.InputSource(new StringReader(strXml)));Hope this helps.

  • How to write a string into an XML

    I wrote a web service to receive a string and write to Oracle Application Server as XML Document. But It is not writing anything. Below is writer program. What do I need to add to make it work
    public class Writer
    public Writer()
    } public void WriteHabFile(String out, String fileName)
    XMLDocument doc = new XMLDocument();
    try
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    public void WriteLanFile(String out2, String fileName2)
    XMLDocument doc = new XMLDocument();
    try
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName2)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    Any help would be greatly appreciated.

    Why don't you try something like:
    public class Writer {
    public Writer(){}
    public void WriteHabFile(String out, String fileName) {
         oracle.xml.parser.v2.DOMParser parser = new oracle.xml.parser.v2.DOMParser();
         try {
              parser.parse(new BufferedReader(new StringReader(out)));
         catch(XMLParseException xe) {
              // Do Something
         catch(SAXException se) {
              // Do Something
         catch(IOException ie) {
              // Do Something
         XMLDocument doc = parser.getDocument();
    try {
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    public void WriteLanFile(String out2, String fileName2) {
         oracle.xml.parser.v2.DOMParser parser = new oracle.xml.parser.v2.DOMParser();
         try {
              parser.parse(new BufferedReader(new StringReader(out)));
         catch(XMLParseException xe) {
              // Do Something
         catch(SAXException se) {
              // Do Something
         catch(IOException ie) {
              // Do Something
         XMLDocument doc = parser.getDocument();
    try {
    XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName2)));
    output.setEncoding("utf-8");
    output.printDocument(doc);
    output.close();
    catch (Exception e)
    System.out.println(e.toString());
    Hope this helps,
    Mark Brown

  • XML: How to convert xml string into Node/Document

    I have a string in xml form.
    <name>
    <first/>
    <second/>
    </name>
    I want to convert this string into DOM Node or Document.
    How can I do this?
    Any help or pointer?
    TIA
    Sachin

    Try this :
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new org.xml.sax.InputSource(new StringReader(strXml)));Hope this helps.

Maybe you are looking for

  • Blu-Ray export fails.

    This is a strange and *very* frustrating problem. I'll choose Share >> Blu-Ray and select the Output Device as "Hard Drive (Blu-Ray)". Now, this used to work: it would create a disk image. Now, after having made no discernible changes to FCP X or any

  • Taking more time to pull records from Order Management to Receivables

    Hello Everybody. We have a legacy system, which pulls the data into OM creating Orders and taking very long time to push them into Receivables. Please provide the activities to be performed so as to improve the process. Thanks in Advance.

  • Moving songpositionline in small increments? how to?

    Hi I`d like to be in the matrix window playing MIDI info direct into the score. But how to move the song position line in smaller increments than a bar. preferable moving in correspondance with the Grid value/zoom yours Bo

  • User defined rule for missing triples

    Hi, i would like to know if there is a way to define a user defined rule for triples that are not contained in a model. With curly brace syntax it could be something like this: INSERT INTO mdsys.semr_validation_rb VALUES( 'test_rule', '{?s ?p ?o. OPT

  • IMPORT FROM 8.1.5 (NT) TO 8.1.6 ( AIX) PROBLEM

    WHEN I TRY TO IMPORT 8.1.5 (NT) DATABASE TABLE TO 8.1.6 ( AIX) DATABASE, IT GIVES THE FOLLOWING ERROR, IMP-00002: failed to open transformer.dmp for read CAN'T I IMPORT TABLES FROM 8.1.5 TO 8.1.6 ?