2014-02-09 39 views
0

我的問題不是關於xpath語法,而是涉及xpath周圍的java API。考慮下面的XML:Java XPath API - 獲取表示子樹的字符串

<wrapper> 
    <metadata> 
     <somefield>somevalue</somefield> 
     <anotherfield>othervalue</anotherfield> 
    </metadata> 
    <data> 
     <some> 
      <unique> 
       <xml> 
        <structure>stuff</structure> 
       </xml> 
      </unique> 
     </some> 
    </data> 
</wrapper> 

我可以很容易地得到使用XPath通過使用下面的代碼中的元數據字段:

XPath xp = XPathFactory.newInstance().newXPath(); 
Node node = (Node) xp.evaluate("/wrapper/metadata/somefield", xmlDoc, XPathConstants.NODE); 
String somefield = node.getFirstChild().getNodeValue(); 

我與我怎麼能得到代表的字符串掙扎xml從<some>標籤開始。換句話說,我寫了什麼代碼來獲得打印出來的字符串時,會打印出以下內容? xpath查詢將是「/ wrapper/data/some」,但我不知道如何恰當地使用xpath api。

<some> 
    <unique> 
     <xml> 
      <structure>stuff</structure> 
     </xml> 
    </unique> 
</some> 
+0

使用XPath獲取'some'標記,然後使用Transformer將DOM轉換爲'String'表示。 [這應該有所幫助](http://stackoverflow.com/questions/2567416/document-to-string)。 –

+0

感謝您的評論蜘蛛。我不知道變壓器。 – Russ

回答

4

您只需使用Transformer作爲你,如果你正在寫的文件到文件的Node你從XPathExpression迴轉變爲String,這裏是一個完整的例子:

public static void main(String[] args) throws Exception { 
    final String xml = "<wrapper>\n" 
      + " <metadata>\n" 
      + "  <somefield>somevalue</somefield>\n" 
      + "  <anotherfield>othervalue</anotherfield>\n" 
      + " </metadata>\n" 
      + " <data>\n" 
      + "  <some>\n" 
      + "   <unique>\n" 
      + "    <xml>\n" 
      + "     <structure>stuff</structure>\n" 
      + "    </xml>\n" 
      + "   </unique>\n" 
      + "  </some>\n" 
      + " </data>\n" 
      + "</wrapper>"; 
    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8))); 
    final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//some"); 
    final Node node = (Node) xpath.evaluate(doc, XPathConstants.NODE); 
    StringWriter sw = new StringWriter(); 
    TransformerFactory tf = TransformerFactory.newInstance(); 
    Transformer transformer = tf.newTransformer(); 
    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 
    transformer.transform(new DOMSource(node), new StreamResult(sw)); 
    System.out.println(sw.toString()); 
}