java - XPath 从父节点和子节点选择属性值

标签 java xml xpath xml-parsing

以下是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
   <query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:lang="en-GB">
      <results>

        <sector sectorid="1" sectorname="Basic Materials">
          <industry id="112" name="Agricultural Chemicals"/>
          <industry id="132" name="Aluminum"/>
          <industry id="110" name="Chemicals - Major Diversified"/>
          <industry id="131" name="Copper"/>
          <industry id="134" name="Gold"/>
          <industry id="121" name="Independent Oil and Gas"/>
          <industry id="120" name="Major Integrated Oil and Gas"/>
        </sector>

        <sector sectorid="2" sectorname="Conglomerates">
          <industry id="210" name="Conglomerates"/>
        </sector>

        <sector sectorid="7" sectorname="Services">
          <industry id="720" name="Advertising Agencies"/>
          <industry id="773" name="Air Delivery and Freight Services"/>
          <industry id="772" name="Air Services and Others"/>
          <industry id="730" name="Apparel Stores"/>
          <industry id="744" name="Auto Dealerships"/>
        </sector>

     </results>
   </query>

从上面的 XML 文件中,我希望将属性值存储在适当的变量中:sectorididname (我使用的是Java)。我一直在研究不同的 XPath 表达式,并想出了以下代码,但是,在存储 的值时,会引发 java.lang.NumberFormatException: For input string: "" 异常id 属性。这是我的代码:

public class XMLToDatabase {

    private static int __SectorID;
    private static int __IndustryID;
    private static String __IndustryName;

    public static void main(String[] args) throws SQLException, UnsupportedEncodingException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {

        try {               
            File _XMLFile = new File("SectorsAndIndustries.xml");

            DocumentBuilderFactory _DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            _DocumentBuilderFactory.setNamespaceAware(true);

            DocumentBuilder _DocumentBuilder = _DocumentBuilderFactory.newDocumentBuilder();
            Document _Document = _DocumentBuilder.parse(_XMLFile);  

            _Document.getDocumentElement().normalize();

            XPath _XPath = XPathFactory.newInstance().newXPath();

            XPathExpression _XPathExpression = _XPath.compile("//sector | //industry");

            NodeList _NodeList = (NodeList) _XPathExpression.evaluate(_Document, XPathConstants.NODESET);


            for (int i = 0; i < _NodeList.getLength(); i++) {
                Node _Node = _NodeList.item(i);

                if(_Node.getNodeType() == Node.ELEMENT_NODE) {
                    Element _Element = (Element) _Node;

                    __SectorID = Integer.parseInt(_Element.getAttribute("sectorid"));
                    __IndustryID = Integer.parseInt(_Element.getAttribute("id"));
                    __IndustryName = _Element.getAttribute("name");
                }

            System.out.println(__SectorID + ", " + __IndustryID + ", " + __IndustryName);
            }
        } catch (Exception e) {
             e.printStackTrace();
        }

    }

}

有人可以帮我确定是否是 XPath 表达式 导致了我的错误,或者是否是我存储第二个变量 __IndustryID 的方式?因为第一个变量__SectorID正确存储了值1,但抛出了上面提到的__IndustryID异常。理想情况下,我希望在每次执行 for 循环时存储所有 3 个属性的值,以将它们保存到数据库表中。如果需要更多信息,请告诉我。

最佳答案

据我所知,您正在编译一个节点列表,其中的节点是 sectorindustry 元素。对于其中每一个,您都希望检索 sectoridid 属性 - 但显然,没有元素同时具有这两个属性。

更好的方法是

  • 找到所有sector元素,并为每个元素打印出扇区ID
  • 对于每个 sector 元素,遍历其所有名为 industry 的子元素(这需要对每个 sector 元素应用第二个 XPath 表达式,但是这是一个微不足道的问题:"industry")
  • 并输出每个行业的ID属性

关于java - XPath 从父节点和子节点选择属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447911/

相关文章:

Google Docs ImportXML 的 XPath 查询

java - Swing、Java 和多线程以及着色按钮

java - 安全连接Java Socket

Java构造http请求报文

google-sheets - 如何在 Google 表格中获取消费者价格指数 (CPI)?

java - 这个 xpath 看起来正确吗?

java - 整数和字符原始包装类命名的原因

java - 在android中调用soap webservice

javascript - Wolfram API 跨源问题

java - Android 应用程序教程 content.xml 和 activity.xml 文件与教程有不同的代码