开发者

Node to string without parent information

I use xpath to get a NodeList. Then I use this code to get a string representation, but it also has the parent nodes.

StringWriter sw = new StringWriter();
    try {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return sw.toString();

How can I only get the self or decendant开发者_如何学运维 as string? And maybe steal the namespace declariations from the parent?


You don't show how the nodes in the node-set were selected. Most probably they are elements and this is the cause of your problem.

The solution is simple:

Construct and use an XPath expression that selects only the wanted text nodes.

For example, instead of :

/x/y/z

use

/x/y/z/text()

The last expression selects any text node that is a child of any element named z that is a child of any element named y that is a child of the top element, named x.

UPDATE:

The OP has clarified in a comment:

"Thanks, I tried this, but it only gives my real text in node. I want a string reresentation of everything (nodes and text) in the current node, without the information of the parent nodes. E.g if I would just have a xml file and open it with a text editor and then copy out some subtree. Do you know what I'm talking about?"

This can be accomplished in XSLT, using

<xsl:copy-of select="yourExpression/node()"/> 

Alternatively, if your XML API allows it, for every selected node use:

theSelectedNode.InnerXml
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜