Ajay
Ajay

Reputation: 795

Java - Extract child elements

I am new in Java and need to parse the below XML file

<foo>
    <foo1>
        <tag1>1</tag1>
        <tag2>2</tag2>
    </foo1>

    <foo2>
        <element1>aaa</element1>
        <element1>bbb</element2>
    </foo2>

</foo>

I need

<foo1>
    <tag1>1</tag1>
    <tag2>2</tag2>
</foo1>

<foo2>
    <element1>aaa</element1>
    <element1>bbb</element2>
</foo2>

as output. I was able to get the values of nodes but not desired output. Please help me out.. Thanks.

Upvotes: 2

Views: 189

Answers (2)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

OK, I think I got it. Here's the code with documentation:

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

    // parse input XML file into Document
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("C://Temp/xx.xml");

    // build a formatted XML String 
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(doc), result);
    String xmlString = result.getWriter().toString();

    // Split the formatted-XML-String according to new-line
    String lines[] = xmlString.split("\\r?\\n");
    // rebuild the String, skipping undesired lines
    xmlString = "" ;
    String newLine = String.format("%n");
    for (int i = 2 ; i < lines.length-1 ; i++) {
        xmlString += lines[i] + newLine;
    }
    System.out.println(xmlString);

Upvotes: 1

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

Since in your case, you desire an invalid XML as output, I suggest you don't parse the XML file. Just read the entire file line-by-line and build the desired String by skipping first and last lines

Upvotes: 0

Related Questions