2011-08-10 26 views
2

鑑於這樣的XML:選擇XML的原始文本

<container> 
    <item> 
     <xmlText> 
      <someTag>   
       <otherTag> 
        Text 
       </otherTag> 
      </someTag> 
     </xmlText> 
    </item> 
<container> 

我想選擇所有文字是項/ XMLTEXT。我想打印此節點的所有內容標籤(someTag,otherTag)。

我寧願用XPath處理這個問題,但這是Java程序的一部分,所以如果有這樣的機制,我可以把它也包括在內。

+0

好問題,+1。查看我的答案,瞭解簡單易用的XSLT解決方案。 :) –

回答

0

使用XSLT此

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="/"> 
    <xsl:copy-of select="/container/item/xmlText/node()"/> 
</xsl:template> 
</xsl:stylesheet> 

當此所提供的XML文檔應用(糾正爲格式正確!!!):

<container> 
    <item> 
     <xmlText> 
      <someTag> 
       <otherTag> 
       Text 
       </otherTag> 
      </someTag> 
     </xmlText> 
    </item> 
</container> 

想要的,正確的re sult is

<someTag> 
    <otherTag> 
       Text 
       </otherTag> 
</someTag> 
0

如果這是你的元素使用XPath檢索

XPathFactory factory = XPathFactory.newInstance(); 
XPath xpath = factory.newXPath(); 

Element element = (Element) xpath.evaluate(
    "/container/item/xmlText", document, XPathConstants.NODE); 

然後,你可以做一些沿着這些路線:

java.io.ByteArrayOutputStream data = 
    new java.io.ByteArrayOutputStream(); 
java.io.PrintStream ps = new java.io.PrintStream(data); 

// These classes are part of Xerces. But you will find them in your JDK, 
// as well, in a different package. Use any encoding here: 
org.apache.xml.serialize.OutputFormat of = 
    new org.apache.xml.serialize.OutputFormat("XML", "ISO-8859-1", true); 
org.apache.xml.serialize.XMLSerializer serializer = 
    new org.apache.xml.serialize.XMLSerializer(ps, of); 

// Here, serialize the element that you obtained using your XPath expression. 
serializer.asDOMSerializer(); 
serializer.serialize(element); 

// The output stream now holds serialized XML data, including tags/attributes... 
return data.toString(); 

UPDATE

這將是更簡潔,而比使用Xerces內部。這是相同的Dimitre的解決方案,只是沒有使用XSLT樣式表,但所有的Java:

ByteArrayOutputStream out = new ByteArrayOutputStream(); 
Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
Source source = new DOMSource(element); 
Result target = new StreamResult(out); 
transformer.transform(source, target); 

return out.toString(); 
+0

這標誌着很多的方法和類,不是有更好的辦法嗎? –

+0

什麼是棄用?使用Xerces 2.7.1(不是最新版本)和Java 6,我在這裏看不到任何棄用 –

+0

這些類在我的實例中已棄用: import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; –