Java odftoolkit, как добавить созданный узел из простой строки в документ odf
У меня есть код:
// -----------------------------------------------------------------
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?
1 ответ
Решение
У меня есть решение от Сванте Шуберта из группы рассылки odf-users:
Хитрость заключается в том, чтобы сделать пространство имен 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 (новый StringReader(фрагмент))). 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()))