开发者

Selecting xml raw text

开发者 https://www.devze.com 2023-03-27 04:27 出处:网络
Given xml like this: <container> <item> <xmlText> <someTag开发者_如何学C> <otherTag>

Given xml like this:

<container>
    <item>
        <xmlText>
            <someTag开发者_如何学C>           
                <otherTag>
                    Text
                </otherTag>
            </someTag>
        </xmlText>
    </item>
<container>

I would like to select all text that is under item/xmlText. I would like to print all the content of this node with tags (someTag, otherTag).

I would prefer to handle with this with XPath, but this is part of Java program, so if there is such mechanism I could take it as well.


Use XSLT for this:

<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>

When this is applied on the provided XML document (corrected to be well-formed !!!):

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

the wanted, correct result is produced:

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


When this is your Element retrieved with XPath

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

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

Then, you can do something along these lines:

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

This would be more concise, rather than using Xerces internals. It's the same as Dimitre's solution, just not with an XSLT stylesheet but all in 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

精彩评论

暂无评论...
验证码 换一张
取 消