簡體   English   中英

使用DOM解析XML並在Java中打印

[英]Parse XML using DOM and print in java

我嘗試了很多使用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");

也..我在打印時為空

您在這里混合模型。 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());
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM