考虑到我有 2 个具有相同结构但没有 dtd 的 xml 文件
xml1:
<DigestType name="Blogs">
<From>xxx@xx.org</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>xxx@xx.org</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>
现在我想将这两个 xml 合并为一个
<DigestType name="Blogs">
<From>xxx@xx.org</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 格式不正确;我假设元素开始的名称是正确的。)
关于java - 我如何在java中将多个xml合并为单个xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193384/