使用JAVA合并多个XML文件的不同节点
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用JAVA合并多个XML文件的不同节点,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2379字,纯文字阅读大概需要4分钟。
内容图文
![使用JAVA合并多个XML文件的不同节点](/upload/InfoBanner/zyjiaocheng/678/f304f0083a614d81bb73c58a28ad9b99.jpg)
我在arrayList中有一些xml文件,例如A.xml B.xml
我想合并一些节点,而其余部分则保留为使用java时的样子.我是新手,所以不知道该怎么做.
xml:
<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
bool A, B;
bool C;
</declaration>
<template>
<location id="1" x="10" y="10"/>
<transition>
<source ref="3"/>
</transition>
</template>
<system> system AND;</system>
</nta>
B.xml:
<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
int f,k;
bool D;
</declaration>
<template>
<location id="100" x="40" y="89"/>
<transition>
<source col="9"/>
</transition>
</template>
<system> system OR;</system>
</nta>
并输出:
<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
bool A, B;
bool C;
int f,k;
bool D;
</declaration>
<template>
<location id="1" x="10" y="10"/>
<transition>
<source ref="3"/>
</transition>
</template>
<template>
<location id="100" x="40" y="89"/>
<transition>
<source col="9"/>
</transition>
</template>
<system> system AND, OR;</system>
</nta>
基本上,我想将声明和系统以及其余部分合并到输出xml文件中以串行方式进行.如何使用JAVA做到这一点?抱歉,很长的帖子!!!
解决方法:
与其他可用的XML处理API相比,对我来说,
使用DOMBuilder和SAXBuilder JDOM的用户更适合:
>修改XML文档
> XML树遍历和对任何部分的随机访问
>合并文件
这是合并两个XML文档的完整工作示例:
SAXBuilder builder = new SAXBuilder();
Document doc1 = builder.build(new File("E:\\XML1.xml"));
Document doc2 = builder.build(new File("E:\\XML2.xml"));
String rootName = doc1.getRootElement().getName();
Element newRoot = new Element(rootName);
Document newDoc = new Document(newRoot);
Element root1 = doc1.getRootElement();
Element root2 = doc2.getRootElement();
// creating declaraion element by merging the declaration content
Element declaration = new Element("declaration");
declaration.addContent(root1.getChildText("declaration"));
declaration.addContent(root2.getChildText("declaration"));
newRoot.addContent(declaration); // add declaration element to new document
newRoot.addContent(root1.getChild("template").clone());
// directly adding template from document XML1,
//after getting template child,
//it needs to be cloned to detached from its parent
newRoot.addContent(root2.getChild("template").clone());
// same for document XML2
/*** now code yourself for system element here ***/
XMLOutputter outputter = new XMLOutputter();
outputter.output(newDoc, System.out);
// output the new doc, pass your OutputStream to this function
内容总结
以上是互联网集市为您收集整理的使用JAVA合并多个XML文件的不同节点全部内容,希望文章能够帮你解决使用JAVA合并多个XML文件的不同节点所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。