0

我有一个代码:

// -----------------------------------------------------------------

TextDocument resDoc = TextDocument.loadDocument( someInputStream );

Section section = resDoc.getSectionByName( "Section1" );  // this section does exist in the document

// create new node form String

String fragment = "<text:p text:style-name=\"P13\"><text:span text:style-name=\"T1\">Test</text:span></text:p>";

Node node = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new InputSource( new StringReader( fragment ) ) ).getDocumentElement();
node = section.getOdfElement().getOwnerDocument().importNode( node, true );

// append new node into section

section.getOdfElement().appendChild( node );

// -----------------------------------------------------------------

代码运行没有问题。但是结果文档的部分中没有出现任何内容。请知道如何将从字符串创建的新节点添加到 odf 文档中?

4

1 回答 1

1

我从 odf-users 邮件组获得了 Svante Schubert 的解决方案:

诀窍是使 DocumentFactory 命名空间感知,此外,将命名空间添加到您的文本片段。详细地说,这正在改变:

老的:

String fragment = "<text:p text:style-name=\"P13\"><text:span text:style-name=\"T1\">Test</text:span></text:p>";
Node node = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new

InputSource(new StringReader(fragment ))).getDocumentElement();

新的:

String fragment = "<text:p xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" text:style-name=\"P13\"><text:span text:style-name=\"T1\">Test</text:span></text:p>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);

所以根据他的发现,我想出了一个方法:

private Node importNodeFromString( String fragment, Document ownerDokument ) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware( true );

    Node node;
    try {
        node = dbf.newDocumentBuilder().parse( new InputSource( new StringReader( fragment ) ) ).getDocumentElement();
    }
    catch ( SAXException | IOException | ParserConfigurationException e )                {
        throw new RuntimeException( e );
    }

    node = ownerDokument.importNode( node, true );
    return node;
}

这可以用作:

section.getOdfElement().appendChild(importNodeFromString(fragmment, section.getOdfElement().getOwnerDocument()))
于 2018-05-23T09:19:00.947 回答