选择xml原始文本

时间:2011-08-10 09:19:12

标签: java xml xslt xpath xml-serialization

给出像这样的xml:

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

我想选择item / xmlText下的所有文字。我想打印此节点的所有内容标签(someTag,otherTag)。

我更愿意用XPath处理这个问题,但这是Java程序的一部分,所以如果有这样的机制我也可以接受它。

2 个答案:

答案 0 :(得分: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();

<强>更新

这将更简洁,而不是使用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();

答案 1 :(得分: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>

产生了想要的正确结果

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