chinna_82
chinna_82

Reputation: 6403

Java - XML read root element value

<?xml version="1.0" encoding="UTF-8"?>
<JDF DescriptiveName="DescriptiveName" ID="n0001" JobID="1101-CCC-0" JobPartID="1" ProjectID="">
<Comment Name="Materialnummer">XXXXXXX</Comment>
<NodeInfo LastEnd="2014-03-12T18:00:00+01:00">
<EmployeeRef rRef="EMPCSR"/>
</NodeInfo>
<CustomerInfo CustomerID="1740">
</CustomerInfo>
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
<JDF Category="FinalImaging" ID="n0002" Status="Waiting" Type="ProcessGroup" Types="XXX">
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
</JDF>
<JDF ID="n0002" Status="Waiting" Type="ProcessGroup" Types="PrePressPreparation">
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
</JDF>
</JDF>

How do I get the root element value. For this example I want to get the DescriptiveName,ID,JobID and ProjectID. I managed to read other values but stuck in root emlement. Please advice. EDITED

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = builderFactory.newDocumentBuilder();
                Document xmlDocument = builder.parse(file);
                XPath xPath = XPathFactory.newInstance().newXPath();
                //System.out.println("*************************");
                String expression = "/JDF";
                NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

Upvotes: 0

Views: 3346

Answers (1)

stacky
stacky

Reputation: 820

A sample here :

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

    public class Main {
      public static void main(String[] argv) throws Exception{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);

        factory.setExpandEntityReferences(false);

        Document doc = factory.newDocumentBuilder().parse(new File("filename"));

        Element root = null;

        NodeList list = doc.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
          if (list.item(i) instanceof Element) {
            root = (Element) list.item(i);
            break;
          }
        }
        root = doc.getDocumentElement();
      }
    }

You can get the attributes from root object

Upvotes: 1

Related Questions