8

I have the following question:

I would like to check, whether a XML document contains a specific XML element. Is it possible to check, for example with a java method of a specific API, which returns a boolean value, wheter a specific XML element are available in a XML document?

This is my XML document as example:

<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ServiceRequest>      
     <RequestPayload>
        <LocationInformationRequest>
            <InitialInput>
                <GeoRestriction>
                    <Area>
                        <PolylinePoint>
                            <Longitude>11.0</Longitude>
                            <Latitude>12.0</Latitude>
                            <Altitude>13.0</Altitude>
                        </PolylinePoint>                            
                    </Area>
                </GeoRestriction>
            </InitialInput>
        </LocationInformationRequest>
     </RequestPayload>
  </ServiceRequest>
</Test>

I need the information as a boolean value, wheter the XML element Area are existing or not existing. The XML Document is used in my own java classes as a type of string.

Thanks for help !

5 Answers 5

6
public boolean isElementExists(String content) {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    Document inputDoc = documentBuilderFactory.newDocumentBuilder().parse(new StringReader(content));
    NodeList nodeList = inputDoc.getElementsByTagName(tagName);
    return nodeList.getlength() == 0 ? true : false;
}
Sign up to request clarification or add additional context in comments.

Comments

4

Since the document is a string and assuming you don't need to parse it for other reasons, I would use the StAX API:

  public static boolean hasElement(String document, String localName)
      throws XMLStreamException {
    Reader reader = new StringReader(document);
    XMLStreamReader xml = XMLInputFactory.newFactory()
                                         .createXMLStreamReader(reader);
    try {
      while (xml.hasNext()) {
        if (xml.next() == XMLStreamConstants.START_ELEMENT
            && localName.equals(xml.getLocalName())) {
          return true;
        }
      }
    } finally {
      xml.close();
    }
    return false;
  }

The advantage of this API over the SAX parse is that because it is a pull parser it is possible to stop processing the document before completion without using an artificial mechanism like throwing an exception.

Comments

2

You can execute XPath queries with Javax XPath (there are other XPath API's too):

http://docs.oracle.com/javase/6/docs/api/javax/xml/xpath/package-summary.html

Comments

2

If this is all u need, u could write ur own function:

If (xmlobjectstring.contains("<Area>") and xmlobjectstring.contains("</Area>") { }

Than u just need to parse out the different objects from the xmlfile.

You could also try out the SAX-XML Reader:

http://blog.mynotiz.de/programmieren/java-sax-parser-tutorial-773/

If it gets more complicated you will need to use xpath:

http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html

Comments

1

Two ways, you could try the Java Scanner class to look for a specific string (e.g Longitude) assuming the existence of this word in the document implies the element exists.

Or you could define a SAXParser that uses a custom handler to go through every element in the XML file but that may be too complicated for what you want to do.

1 Comment

In the general case scanning the document as text leaves you vulnerable to false positives because a match can legally be contained in CDATA sections or comments. The SAX approach is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.