【问题标题】:How to print values within XML tag in java [duplicate]如何在java中打印XML标签中的值[重复]
【发布时间】:2014-05-04 19:58:49
【问题描述】:

我真的不知道如何使用 XML 标签。如何遍历节点并在 XML 标签中打印特定节点。下面是 XML 文件。

<Employees>
<Employee>
    <Gender></Gender>
    <Name>
        <Firstname></Firstname>
        <Lastname></Lastname>
    </Name>
    <Email></Email>
    <Projects>
        <Project></Project>
    </Projects>
    <PhoneNumbers>
        <Home></Home>
        <Office></Office>
    </PhoneNumbers>
</Employee>

没有数据,但这是结构。我正在使用以下代码部分解析它。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDocument = builder.parse("employees.xml");
System.out.println(xmlDocument.getDocumentElement().getNodeName());

我想打印性别和姓氏值。如何解析名称标签内的标签,而名称标签内又是员工标签。

问候。

【问题讨论】:

    标签: java xml


    【解决方案1】:

    您应该使用 XPATH。 this post有很好的解释。

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(<uri_as_string>);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(<xpath_expression>);
    

    【讨论】:

      【解决方案2】:

      试试这个。

          String expression = "/Employees/Employee/Gender"; //read Gender value
      
          NodeList nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
          for (int j = 0; nList != null && j < nList.getLength(); j++) {
              Node node = nList.item(j);
              System.out.println("" + node.getFirstChild().getNodeValue());
          }
      
          expression = "/Employees/Employee/Name/Lastname"; //read Lastname value
      
          nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
          for (int j = 0; nList != null && j < nList.getLength(); j++) {
              Node node = nList.item(j);
              System.out.println("" + node.getFirstChild().getNodeValue());
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 2019-12-02
        • 2021-04-21
        相关资源
        最近更新 更多