This discussion is archived
1 Reply Latest reply: Jul 29, 2013 12:39 AM by 912886 RSS

Best way to split xml

pedro.riky Newbie
Currently Being Moderated

Hi all

  i have a xml String thath contain something like this:

 

 

[code]

     <root>

              <a>

                        <b></b>

                        <c></c>

                        <d></d>    

               </a>

              <a>

                        <b></b>

                        <c></c>

                        <d></d>    

               </a>

</root>

[/code]

 

I need to split and get the <a>  tag with all subtags, like a string.

 

How i can do?

  • 1. Re: Best way to split xml
    912886 Newbie
    Currently Being Moderated

    /*Sample XML Below:

     

    <?xml version="1.0" encoding="UTF-8"?>

    <root>

      <a>

      <b>Test B1</b>

      <c>Test C1</c>

      <d>Test D1</d>

      </a>

      <a>

      <b>Test B2</b>

      <c>Test C2</c>

      <d>Test D2</d>

      </a>

      <a>

      <b>Test B3</b>

      <c>Test C3</c>

      <d>Test D3</d>

      </a>

    </root>

    */

     

    import java.io.File;

    import javax.xml.parsers.DocumentBuilderFactory;

    import javax.xml.parsers.DocumentBuilder;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

    public class xmlParsing {

      public static void main(String args[]) {

      try {

      File xmlFile = new File(

      "C:\\test.xml");

      DocumentBuilderFactory dbFactory = DocumentBuilderFactory

      .newInstance();

      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

      Document doc = dBuilder.parse(xmlFile);

     

      doc.getDocumentElement().normalize();

      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

      NodeList nList = doc.getElementsByTagName("a");

      for (int i = 0; i < nList.getLength(); i++) {

      Node nNode = nList.item(i);

      if (nNode.getNodeType() == Node.ELEMENT_NODE) {

      System.out.println("Data of Node: "+(i+1));

      Element element = (Element) nNode;

      System.out.println("B " + element.getElementsByTagName("b").item(0).getTextContent());

      System.out.println("C " + element.getElementsByTagName("c").item(0).getTextContent());

      System.out.println("D " + element.getElementsByTagName("d").item(0).getTextContent());

      }

      }

      } catch (Exception e) {

      System.out.println(e);

     

     

      }

      }

    }

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points