如何使用java检索具有命名空间的XML元素属性?

时间:2015-03-03 00:10:04

标签: java xml xslt

我有以下xml,我正在尝试使用java代码检索BoostBuryDimensionValue标记下的id值,但不返回任何内容。 有人可以帮我这个。提前谢谢。

输入XML

 <?xml version="1.0" encoding="UTF-8"?>
<ContentItem type="OrganicZoneContent" xmlns="http://endeca.com/schema/content/2008" >
  <TemplateId>OrganicResults</TemplateId>
  <Name>OrganicResults</Name>
  <Property name="navigation_records">
    <BoostBury rollupKey="grp_id" recspecField="grp_id" xmlns="http://endeca.com/schema/content/xtags/2010">

      <BoostBuryRecords>
        <BoostBuryRecord recordType="CRITERIA" boostBuryType="BOOST">
          <BoostBurySearch terms="null" key="null"/>
          <BoostBuryDimensionValues>
            <BoostBuryDimensionValue id="4294965238" name="career" dimensionName="Occasion"/>
          </BoostBuryDimensionValues>
        </BoostBuryRecord>

      </BoostBuryRecords>
     </BoostBury>
  </Property>
</ContentItem>

我正在使用的java代码是

public static void main(String[] args) throws Exception { 
    InputStream xml = new FileInputStream("tempinput.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    Document doc = db.parse(xml); 
    XPath xpath = XPathFactory.newInstance().newXPath(); 
    XPathExpression expr = xpath.compile("ContentItem/Property[@name='navigation_records']/BoostBury/BoostBuryRecords/BoostBuryRecord/BoostBuryDimensionValues/BoostBuryDimensionValue/@id");
    Object result = expr.evaluate(doc, XPathConstants.STRING); 
    System.out.println("BoostBuryDimensionValue id = " + result);

} 

0 个答案:

没有答案