Archive for the ‘xml’ Category
SyntaxHighlighter
Shame on me! I’ve discovered that wordpress.com provides syntaxHighlighter functionality just today. So I hurry to report that the only 2 posts in this blog, which contain code snippets have been immediately converted:
<a href="http://sevalapsha.wordpress.com/2008/06/26/copy-nodes-xml-documents-java-dom/">
Copying nodes between XML documents with Java DOM
</a>
&
<a href="http://sevalapsha.wordpress.com/2008/08/11/prototype-google-analytics-javascript/">
Prototype styled Google Analytics javascript snippet
</a>
BTW, isn’t it weird I don’t have one snipped in PHP yet?
Copying nodes between XML documents with Java DOM
Today I had an atomic task of creating a most convenient way to copy nodes from one XML document to another with Java’s DOM implementation. Googling did not help me much in it, so I will share the solution here in case someone would be challenged too.
So, imagine you have multiple XML documents like this:
<document>
<section>
<node attribute="value" />
</section>
</document>
…, another one like this:
<storage><sections /></storage>
… and you wish to read the multilple documents and to put the <section> nodes into the <sections> node of the second one respecting all the structure.
To do that you should:
1. Create the XML document builder:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
2. Get the <sections> node of the target file:
File target;
Document targetDom = builder.parse(new InputSource(new FileReader(target));
Node targetSections = targetDom.getElementsByTagName("sections").item(0);
// TODO this is not the best way to use that.
// I advice XPath instead.
3. Iterate over the source files and get the <section> nodes:
File[] sources;
for (File source : sources) {
Node sourceSection = builder.parse(new InputSource(new FileReader(source))
.getElementsByTagName("section").item(0);
// continued inside
}
4. Copy the node into the target document:
targetDom.appendChild(targetDom.adoptNode(section.cloneNode(true))); // 'true' means we want to clone children too
5. Write the target back to the file:
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(targetDom),
new StreamResult(new FileWriter(target))
);
That’s it. Note, this code lacks error handling and probably won’t work directly after copy-paste, but just shows you the usage of the classes.
Blog RSS feed