0

I want to get as a result a TagName "control". I am using XPath to parse my XML file. Currently I get only a blank window, I don't know why.

My XML file:

<tags>
  <row Id="1" TagName="soccer" Count="7" ExcerptPostId="12371" WikiPostId="12370" />
  <row Id="2" TagName="servos" Count="63" ExcerptPostId="186" WikiPostId="185" />
  <row Id="3" TagName="control" Count="394" ExcerptPostId="192" WikiPostId="191" />
  <row Id="5" TagName="gait" Count="4" ExcerptPostId="12362" WikiPostId="12361" />
</tags>

Here is my Main.java

String uri = "/home/files/Tags.xml";

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(uri);
    XPath xPath = XPathFactory.newInstance().newXPath();

    String output = (String) xPath.evaluate("/tags/row[@TagName='control']", doc.getDocumentElement(),
            XPathConstants.STRING);
    System.out.println("My output:" + output);
} catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }

The expected output should be:

My output: control

7
  • Have you tried debugging it? Do you get any exception? Commented Jun 14, 2018 at 22:27
  • Also temporarily add e.printStackTrace() in your catch block so that you can see what exception might be being thrown. Commented Jun 14, 2018 at 22:34
  • just one word: control Commented Jun 14, 2018 at 22:34
  • yes, "My output: control" Commented Jun 14, 2018 at 22:37
  • Your xpath should probably start with a double slash //tags. Commented Jun 14, 2018 at 22:40

1 Answer 1

1

You are getting an exception which you are silently consuming. Add e.printStackTrace() to the catch block to find out what it is.

Assuming you fix that problem, you also appear to be using an xpath to select the text content of an element that is empty (self-closed).

If you want to select the value of an attribute of an element you need to do something like:

/tags/row[@TagName='control']/@TagName

See this SO post for more information: Getting attribute using XPath

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.