Suggestion to parse this XML in Java

后端 未结 3 1089
长发绾君心
长发绾君心 2021-01-25 11:00

Not new to Java; but relatively new to XML-parsing. I know a tiny bit about a lot of the XML tools out there, but not much about any of them. I am also not an XML-pro.

3条回答
  •  广开言路
    2021-01-25 11:49

    If your XML documents are relatively small (as appears to be the case here), I would use the DOM framework and XPath class. Here is some boilerplate DOM/XPath code from one of my tutorials:

    File xmlFile = ...
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(xmlFile);
    
    XPath xp = XPathFactory.newInstance().newXPath();
    String value = xp.evaluate("/path/to/element/text()", doc);
    // .. reuse xp to get other values as required
    

    In other words, basically you:

    • get your XML into a Document object, via a DocumentBuilder;

    • create an XPath object;

    • repeatedly call XPath.evaluate(), passing in the path of the element(s) required and your Document.

    As you see, there's a little bit of fiddliness in getting hold of your Document object and like all good XML APIs, it throws a plethora of silly pointless checked exceptions. But apart from that, it's fairly no-nonsense for parsing simple small to medium XML documents whose structure is relatively fixed.

提交回复
热议问题