1

Suppose I have a String 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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Latmit
  • 11
  • 3
  • For followers, to get a document *from* a string try ` Builder builder = new Builder(); Document doc = builder.build(docStr, null);` – rogerdpack Sep 13 '16 at 16:50

2 Answers2

2

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>
Chris Winters
  • 1,001
  • 1
  • 6
  • 5
  • for followers, `toXML` spits it out as an XML representation, while `toString` does not, just lists the main header. – rogerdpack Sep 13 '16 at 18:04
1

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();
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276