简体   繁体   English

如何使用JxPath和DOM解析器解析XML文件

[英]How to parse XML file with JxPath and DOM parser

I need simple example how can be possible to parse XML files with Java DOM parser and Apache JxPath. 我需要一个简单的例子,如何用Java DOM解析器和Apache JxPath解析XML文件。 I am aware with DOM parser technology, but now I'm trying to integrate JxPath in my source. 我知道DOM解析器技术,但现在我正在尝试将JxPath集成到我的源代码中。

I have searched in a network, but I can't find working example. 我在网络上搜索过,但我找不到工作的例子。

For test I've got this xml: 为了测试我有这个xml:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd gender="male">
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd gender="male">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
</catalog>

Java code: Java代码:

File file = new File("Files/catalog.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try
{
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(file);

    NodeList nList = doc.getElementsByTagName("cd");
    for(int j = 0; j<nList.getLength(); j++){

        Element element = (Element)nList.item(j);
        System.out.println(element.getElementsByTagName("artist").item(0).getTextContent() + "\n");

    }

}
catch (ParserConfigurationException | SAXException | IOException e)
{
    e.printStackTrace();
}

I have read for classes Container, DocumentContainer and JXPathContext , but I will be grateful for some help or for web source with specific working example. 我已阅读过类Container,DocumentContainer和JXPathContext ,但我将非常感谢一些帮助,或者对具有特定工作示例的Web源感兴趣

Here is the example that do similar work as yours. 以下是与您的工作类似的示例。

File file = new File("Files/catalog.xml");
DocumentContainer dc = new DocumentContainer(file.toURI().toURL());
JXPathContext ctx = JXPathContext.newContext(dc);
Iterator iter = ctx.iterate("//cd/artist");
//In this case, following API will return DOM object
//Iterator iter = ctx.selectNodes("//cd/artist").iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());//object type is String
}

Are you sure JXPath is what you need? 你确定JXPath是你需要的吗? JXPath is an Apache library to use XPath expressions on things that aren't necessarily XML, like Java object trees or maps. JXPath是一个Apache库,可以在不一定是XML的东西上使用XPath表达式,比如Java对象树或映射。 If you've created a DOM from your XML, you may as well use the default Java XPath implementation on it. 如果您已经从XML创建了DOM,那么您也可以在其上使用默认的Java XPath实现。 See here: https://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPathFactory.html . 请参见: https//docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPathFactory.html In fact, JXpath would work against you here, because DOM has a tree of objects like Element and Text with metadata like the element name. 实际上,JXpath在这里会对你不利,因为DOM有一个像ElementText这样的对象树,其元数据就像元素名一样。 So instead of getting an expression like //cd/artist you get something like //*[@tagName='cd']/childNodes[@tagName='artist'] . 因此,不要像//cd/artist那样获得类似//*[@tagName='cd']/childNodes[@tagName='artist']的表达式。

Now, if you for some reason have to be able to use XPath expressions on something that might either be a Java object tree, or a DOM, without knowing it up-front, in that case JXPath would be a good use-case in the way beckyang described in their answer: by using the JXPath DocumentContainer to access the document. 现在,如果由于某种原因必须能够在可能是Java对象树或DOM的东西上使用XPath表达式而不事先知道它,那么JXPath将是一个很好的用例。 beckyang在答案中描述的方式:通过使用JXPath DocumentContainer来访问文档。

Yes I read for JxPath from few hours and I now understand the logic of this API 是的,我从几个小时开始阅读JxPath,现在我理解了这个API的逻辑

Much thanks for the answers. 非常感谢你的答案。 Here some code form me 这里有一些代码形成了我

public class Main {
    private final static Logger log = Logger.getLogger(Main.class);

    public static void main(String[] args) {

        PropertyConfigurator.configure("log4j.properties");

        File file = new File("students.xml");
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        try
        {
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(file);

            NodeList nList = doc.getElementsByTagName("cd");
            for(int j = 0; j<nList.getLength(); j++){

                Element element = (Element)nList.item(j);

               JXPathContext context = JXPathContext.newContext(element);
               log.debug(context.getValue("company/address/city[2]"));

            }

        }
        catch (ParserConfigurationException | SAXException | IOException e)
        {
            e.printStackTrace();
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM