代码之家  ›  专栏  ›  技术社区  ›  Bav

如何在nodelist中将xml解析为java

  •  2
  • Bav  · 技术社区  · 7 年前

    这是我的xml

    <?xml version = "1.0" encoding = "UTF-8"?>
     <ns0:GetADSLProfileResponse xmlns:ns0 = "http://">
    <ns0:Result>
        <ns0:eCode>0</ns0:eCode>
        <ns0:eDesc>Success</ns0:eDesc>
    </ns0:Result>
    </ns0:GetADSLProfileResponse> 
    

    这是我用java编写的代码,我需要知道如何从这里开始 我在网上尝试了一些代码,但仍然没有解决我的问题 如何获取结果中的值以在其中循环,并在ecode中获得0,在eDesc中获得成功

    CustomerProfileResult pojo = new CustomerProfileResult();
        String body = readfile();
        System.out.println(body);
        try {  
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dom = db.parse(new InputSource(new StringReader(body)));
            XPath xpath =XPathFactory.newInstance().newXPath();
    
            XPathExpression name = xpath.compile("/xml/GetADSLProfileResponse/Result");
            NodeList nodeName = (NodeList) name.evaluate(dom, XPathConstants.NODESET);
    
            if(nodeName!=null){
    
            } 
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Mincong Huang    7 年前

    总结

    您可以尝试使用以下表达式,该表达式允许您选择节点,而无需考虑命名空间 ns0 :

    /*[local-name()='GetADSLProfileResponse']/*[local-name()='Result']/*
    

    解释

    在您的语法中,有几个部分不正确。让我们一起看看。XPath语法 /xml 表示文档的根节点是 <xml> ,但根元素是 <ns0:GetADSLProfileResponse> ; GetADSLProfileResponse 也不正确,因为XML文件包含命名空间。与相同 Result :

    /xml/GetADSLProfileResponse/Result
    

    在我的解决方案中,我忽略了名称空间,因为您提供的名称空间不完整。以下是一个完整的入门计划:

    String XML =
      "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n"
          + "<ns0:GetADSLProfileResponse xmlns:ns0 = \"http://\">\n"
          + "  <ns0:Result>\n"
          + "    <ns0:eCode>0</ns0:eCode>\n"
          + "    <ns0:eDesc>Success</ns0:eDesc>\n"
          + "  </ns0:Result>\n"
          + "</ns0:GetADSLProfileResponse> ";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document;
    try (InputStream in = new ByteArrayInputStream(XML.getBytes(StandardCharsets.UTF_8))) {
      document = builder.parse(in);
    }
    
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("/*[local-name()='GetADSLProfileResponse']/*[local-name()='Result']/*");
    
    NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node node = nodeList.item(i);
      System.out.println(node.getNodeName() + ": " + node.getTextContent());
    }
    

    它打印:

    ns0:eCode: 0
    ns0:eDesc: Success
    

    另请参见: