我有一个代码:
// -----------------------------------------------------------------
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 );
// -----------------------------------------------------------------
代码运行没有问题。但结果文档的部分中没有任何内容。请知道如何将从string创建的新节点添加到odf文档中?
答案 0 :(得分:1)
我从odf-users邮件组获得了Svante Schubert的解决方案:
诀窍是让DocumentFactory识别命名空间,此外, 在文本片段中添加命名空间。 详细情况正在改变:
OLD:
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();
NEW:
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()))