开发者

XOM get Document to String

开发者 https://www.devze.com 2022-12-18 11:07 出处:网络
Suppose I have a S开发者_StackOverflowtring like this: String from = \"<time><day type=\"tt\">ok</day><time>

Suppose I have a S开发者_StackOverflowtring like this:

String from = "<time><day type="tt">ok</day><time>

Now what I would like to do is to create a XOM document and then return back something like:

String to = documentToString(document)

This string should have only <day type="tt">ok parsed</day>, not with <time>..</time>root element.

I have already created the XOM document but don't know what is the easy way to do the string-conversion part.


The toXML() method is your friend:

import nu.xom.*;
import java.io.StringReader;

public class XomElementAsString
{
    public static void main( final String ... args )  throws Exception
    {
        String from = "<time><day type=\"tt\">ok</day></time>";
        Builder parser = new Builder();
        Document document = parser.build( new StringReader( from ) );
        Element child = document
            .getRootElement()
            .getFirstChildElement( "day" );
        System.out.println( child.toXML() );
    }
}

Output:

<day type="tt">ok</day>


You can use xpath to get the day node:

Nodes nodes = document.query("/time");

You can get the string content of that node with

nodes[0].toXML();
0

精彩评论

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