考虑我有2xml文件具有相同的结构没有dtd
xml1:
<DigestType name="Blogs">
<From>[email protected]</FromEmail>
<EmailTimeStamp></EmailTimeStamp>
<EmailSubject></EmailSubject>
<BlogName href="">Merging XML</BlogName>
<Blog Count="2">
<listPost>
<Title href="">Title</Title>
<CommentCount>10</CommentCount>
<Content>Post content...</Content>
</listBlogPost>
<listPost>
<Title href="">Title1</Title>
<CommentCount>10</CommentCount>
<Content>Post content...</Content>
</listBlogPost>
</Blog>
</DigestType>
xml2:
<DigestType name="Blogs">
<From>[email protected]</FromEmail>
<EmailTimeStamp></EmailTimeStamp>
<EmailSubject></EmailSubject>
<BlogName href="">Merging XML</BlogName>
<Blog Count="2">
<listPost>
<Title href="">Title2</Title>
<CommentCount>1</CommentCount>
<Content>content...</Content>
</listBlogPost>
<listPost>
<Title href="">Title3</Title>
<CommentCount>23</CommentCount>
<Content>content...</Content>
</listBlogPost>
</Blog>
现在我想将这2个xml合并为一个
<DigestType name="Blogs">
<From>[email protected]</FromEmail>
<EmailTimeStamp></EmailTimeStamp>
<EmailSubject></EmailSubject>
<BlogName href="">Merging XML</BlogName>
<Blog Count="4">
<listPost>
<Title href="">Title</Title>
<CommentCount>10</CommentCount>
<Content>Post content...</Content>
</listBlogPost>
<listPost>
<Title href="">Title1</Title>
<CommentCount>10</CommentCount>
<Content>Post content...</Content>
</listBlogPost>
<listPost>
<Title href="">Title2</Title>
<CommentCount>1</CommentCount>
<Content>content...</Content>
</listBlogPost>
<listPost>
<Title href="">Title3</Title>
<CommentCount>23</CommentCount>
<Content>content...</Content>
</listBlogPost>
</Blog>
</DigestType>
我正在使用Java。谁能帮助我找出解决方案。
谢谢
乌玛
最佳答案
使用XPath:
XPath xpath = XPathFactory.newInstance().newXPath();
// load
Document xml1 = (Document) xpath.evaluate("/", new InputSource("xml1.xml"),
XPathConstants.NODE);
NodeList listPosts = (NodeList) xpath.evaluate("/DigestType/Blog/listPost",
new InputSource("xml2.xml"), XPathConstants.NODESET);
// merge
Element blog = (Element) xpath.evaluate("/DigestType/Blog", xml1,
XPathConstants.NODE);
for (int i = 0; i < listPosts.getLength(); i++) {
Node listPost = listPosts.item(i);
blog.appendChild(xml1.adoptNode(listPost));
}
// set count
blog.setAttribute("Count", xpath.evaluate("count(listPost)", blog));
// print
DOMImplementationLS impl = (DOMImplementationLS) xml1.getImplementation();
System.out.println(impl.createLSSerializer().writeToString(xml1));
(您的XML格式不正确;我认为元素开头是正确的名称。)