为什么在解析XML时获取空节点值

时间:2013-12-05 10:09:20

标签: java xml parsing

解析下面的XML .First url-malformed-exception正在解析,所以在代码中而不是给出xml字符串我使用了这段代码

Document doc=dBuilder.parse(newInputSource(newByteArrayInputStream(xmlResponse.getBytes("utf-8"))));

根据此链接

java.net.MalformedURLException: no protocol

现在我将节点值变为null。 我如何克服这个问题。在for循环中的代码中我已经提到过节点的空值即将到来

我正在使用以下代码:

try {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(xmlResponse.getBytes("utf-8"))));
    //read this - https://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    XPath xPath =  XPathFactory.newInstance().newXPath()
    String expression = "/GetMatchingProductForIdResponse/GetMatchingProductForIdResult/Products/Product"
    System.out.println(expression)
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET)
    System.out.println("the size will be of the node list ${nodeList.getLength()}");
    for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getNodeValue()+"the value coming will be "); // here i am getting value null for each node
    }
} catch (Exception e) {
    e.printStackTrace(System.out);
}

解析XML:

<?xml version="1.0"?>
<GetMatchingProductForIdResponse   xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <GetMatchingProductForIdResult Id="H5-9OSH-9NZ7" IdType="SellerSKU" status="Success">
    <Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
    <Product>
      <Identifiers>
        <MarketplaceASIN>
          <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
          <ASIN>B004FQLAH2</ASIN>
        </MarketplaceASIN>
      </Identifiers>
      <AttributeSets>
        <ns2:ItemAttributes xml:lang="en-US">
          <ns2:Binding>Office Product</ns2:Binding>
          <ns2:Brand>Konica-Minolta</ns2:Brand>
          <ns2:Color>Y</ns2:Color>
          <ns2:CPUSpeed Units="MHz">200</ns2:CPUSpeed>
          <ns2:Department>Printers</ns2:Department>
          <ns2:Feature>Amp Up your Output - The magicolor 3730DN business color laser printer outputs at speeds up to 25 ppm in both color and B&W which means you can keep up in just about any business environment.</ns2:Feature>
          <ns2:Feature>Unparalleled Image Quality - High resolution 2400 (equivalent) x 600 dpi printing for great color and clarity in both images and text.</ns2:Feature>
          <ns2:Feature>Happy Planet, Outstanding Printing - Simitri HD Toner with Biomass allows for outstanding printing with the environment in mind.</ns2:Feature>
          <ns2:Feature>Connect quicker - Why wait? Standard Ethernet and high-speed USB 2.0 gets you connected faster than ever before.Specifications</ns2:Feature>
          <ns2:Feature>Type - Full-Color Laser Printer</ns2:Feature>
          <ns2:ItemDimensions>
            <ns2:Height Units="inches">13.62</ns2:Height>
            <ns2:Length Units="inches">20.47</ns2:Length>
            <ns2:Width Units="inches">16.50</ns2:Width>
            <ns2:Weight Units="pounds">56.22</ns2:Weight>
          </ns2:ItemDimensions>
          <ns2:IsAutographed>false</ns2:IsAutographed>
          <ns2:IsMemorabilia>false</ns2:IsMemorabilia>
          <ns2:Label>Konica</ns2:Label>
          <ns2:ListPrice>
            <ns2:Amount>449.00</ns2:Amount>
            <ns2:CurrencyCode>USD</ns2:CurrencyCode>
          </ns2:ListPrice>
          <ns2:Manufacturer>Konica</ns2:Manufacturer>
          <ns2:Model>A0VD017</ns2:Model>
          <ns2:NumberOfItems>1</ns2:NumberOfItems>
          <ns2:OperatingSystem>Windows XP, Vista, 7</ns2:OperatingSystem>
          <ns2:OperatingSystem>Mac X 10.2.8, 10.6+</ns2:OperatingSystem>
          <ns2:PackageDimensions>
            <ns2:Height Units="inches">19.00</ns2:Height>
            <ns2:Length Units="inches">24.20</ns2:Length>
            <ns2:Width Units="inches">22.00</ns2:Width>
            <ns2:Weight Units="pounds">65.30</ns2:Weight>
          </ns2:PackageDimensions>
          <ns2:PackageQuantity>1</ns2:PackageQuantity>
          <ns2:PartNumber>A0VD017</ns2:PartNumber>
          <ns2:ProductGroup>CE</ns2:ProductGroup>
          <ns2:ProductTypeName>PRINTER</ns2:ProductTypeName>
          <ns2:Publisher>Konica</ns2:Publisher>
          <ns2:SmallImage>
            <ns2:URL>http://ecx.images-amazon.com/images/I/21qN3BU-BHL._SL75_.jpg</ns2:URL>
            <ns2:Height Units="pixels">75</ns2:Height>
            <ns2:Width Units="pixels">75</ns2:Width>
          </ns2:SmallImage>
          <ns2:Studio>Konica</ns2:Studio>
          <ns2:Title>Konica Minolta Magicolor 3730DN Color Laser Printer 24PPM 2400X600DPI ENET USB 2.0</ns2:Title>
        </ns2:ItemAttributes>
      </AttributeSets>
      <Relationships/>
      <SalesRankings/>
    </Product>
    </Products>
  </GetMatchingProductForIdResult>
  <ResponseMetadata>
    <RequestId>0b508338-3afe-4178-adc4-60c9c8448987</RequestId>
  </ResponseMetadata>
</GetMatchingProductForIdResponse>

1 个答案:

答案 0 :(得分:14)

DOM中的getNodeValue方法被定义为始终为元素节点返回null(有关详细信息,请参阅the JavaDoc page for org.w3c.dom.Node顶部的表格)。如果您想要元素内的文本,那么您应该使用getTextContent()代替。

您在此回答的评论中添加了第二个问题,询问如何使用XPath搜索具有名称空间前缀的节点,例如ns2:。 XPath 1.0处理命名空间的方式是,未加前缀的名称总是指不在命名空间中的节点,如果要引用命名空间节点,则必须提供命名空间URI到前缀的绑定(在javax.xml.xpath中是NamespaceContext的工作,然后在表达式中使用这些前缀。您在表达式中使用的前缀不必与原始文档使用的前缀相同,只要它们绑定到正确的URI即可。

因此您使用的是原始XPath:

/GetMatchingProductForIdResponse/GetMatchingProductForIdResult/Products/Product

实际上不应该匹配任何内容,因为文档中的GetMatchingProductForIdResponse等元素在命名空间中是,但是你侥幸成功,因为DocumentBuilderFactory是默认的不知道名称空间。这里要做的正确的事情是使用名称空间感知解析器,并为XPath引擎提供合适的名称空间上下文。遗憾的是,核心Java库中没有可用的NamespaceContext默认实现,但是Spring提供了一个方便的SimpleNamespaceContext实现,如果你不想自己动手,可以使用它。

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true); // parse with namespaces
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(xmlResponse.getBytes("utf-8"))));
doc.getDocumentElement().normalize();

XPath xPath =  XPathFactory.newInstance().newXPath();
SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
xPath.setNamespaceContext(nsCtx);
nsCtx.bindNamespaceUri("prod", "http://mws.amazonservices.com/schema/Products/2011-10-01");
nsCtx.bindNamespaceUri("ns2", "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd");
String expression = "/prod:GetMatchingProductForIdResponse/prod:GetMatchingProductForIdResult/prod:Products/prod:Product‌​/prod:AttributeSets/ns2:ItemAttributes/ns2:Binding";
// ...