0

我尝试了很多使用 DOM 解析以下 XML。我无法打印元素的值。谁能帮我打印元素的值。

提前致谢

<tns:CustomerDetails xmlns:xe="http://www.w3.org/2001/04/xmlenc#" xmlns:xd="http://www.w3.org/2000/09/xmldsig#" xmlns:tns="http://abc.com/elements" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pf="http://abc.com/Service">
  <tns:CustomerId>360817</tns:CustomerId>
  <tns:CustomerName>ABC Corp</tns:CustomerName>
  <tns:PAN>awap</tns:PAN>
  <tns:Timestamp>2010-05-20T12:20:19Z</tns:Timestamp>
  <tns:RequestId>397</tns:RequestId>
  <tns:PIN>1234</tns:PIN>
</tns:CustomerDetails>

我的代码

      File infile = new File("D:\\Cust.xml");
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(infile);
  doc.getDocumentElement().normalize();

  System.out.println("root of xml file " +
                     doc.getDocumentElement().getNodeName());
  System.out.println("==========================");

  NodeList list = doc.getElementsByTagName("CustomerDetails");
  System.out.println(list.getLength());
  Element name = doc.getElementById("CustomerId");
  if (name == null) {
    System.out.println("There is no element with the ID ");
  } else {
    Text text = (Text)name.getFirstChild();
    System.out.println("The ID " + " locates the name " + text.getData());
  }

我试过了

Element name = doc.getElementById("tns:CustomerId");

也..我在打印时得到空值

4

1 回答 1

0

你在这里混合你的模型。 getElementById适用于具有由文档的 DTD 标识为 ID 的属性的元素,并且由于您的文档没有 DTD,因此它永远不会为您提供任何有用的东西。

因为您的文档使用命名空间,您应该使用“NS”方法来提取元素,并且对于包含在元素中的文本,您可以使用getTextContent

  File infile = new File("D:\\Cust.xml");
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  // namespaces - DocumentBuilderFactory is *not* namespace aware by default
  dbFactory.setNamespaceAware(true);
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(infile);
  doc.getDocumentElement().normalize();

  System.out.println("root of xml file " +
                     doc.getDocumentElement().getNodeName());
  System.out.println("==========================");

  NodeList list = doc.getElementsByTagNameNS(
        "http://abc.com/elements", "CustomerDetails");
  System.out.println(list.getLength());
  for(int i = 0; i < list.getLength(); i++) {
    Element custDetails = (Element)list.item(i);
    Element id = custDetails.getElementsByTagNameNS(
        "http://abc.com/elements", "CustomerId").item(0);
    System.out.println("Customer ID: " + id.getTextContent());
    Element name = custDetails.getElementsByTagNameNS(
        "http://abc.com/elements", "CustomerName").item(0);
    System.out.println("Customer Name: " + name.getTextContent());
  }
于 2013-02-05T13:38:26.630 回答