发布于2024-12-03 10:16 阅读(87) 评论(0) 点赞(20) 收藏(2)
我想合并两个 XML 文件(源文件和临时文件)并将结果文件放在源文件中,并且源文件和临时文件具有相同的元素但具有不同的值,例如:
源.xml:
<Main>
<source>
<param>
<entry>
<key> bla1 </key>
<value> bla1 </value>
</entry>
</param>
<Name> name1 </Name>
</Source>
</Main>
和temp.xml:
<Main>
<source>
<param>
<entry>
<key> bla2 </key>
<value> bla2 </value>
</entry>
<entry>
<key> bla3 </key>
<value> bla3 </value>
</entry>
</param>
<Name> name2 </Name>
</Source>
</Main>
我想要的期望输出是这样的:
<Main>
<source>
<param>
<entry>
<key> bla1 </key>
<value> bla1 </value>
</entry>
</param>
<Name> name1 </Name>
</Source>
<source>
<param>
<entry>
<key> bla2 </key>
<value> bla2 </value>
</entry>
<entry>
<key> bla3 </key>
<value> bla3 </value>
</entry>
</param>
<Name> name2 </Name>
</Source>
</Main>
我正在使用此代码,但它根本不影响source.xml :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class MergeXml {
private static final String fileName = "Source.xml";
private static final String tempName = "temp.xml";
private static final String mainTag = "XmlSource";
private static final String YES = "yes";
public void mergeXML() throws ParserConfigurationException, SAXException,
IOException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
Document doc2 = null;
db = dbf.newDocumentBuilder();
doc = db.parse(new File(fileName));
doc2 = db.parse(new File(tempName));
Element tag = doc.createElement(mainTag);
NodeList nodeList = doc2.getElementsByTagName("*");
for(int i =0 ; i < nodeList.getLength(); i++){
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = node.getNodeName();
Element tagChild = doc.createElement((nodeName));
tag.appendChild(tagChild);
}
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, YES);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
}
}
如果需要的话,我的 XML 原始文件:
<XmlSource>
<hostName>api.worldweatheronline.com</hostName>
<parameters>
<entry>
<key>num_of_days</key>
<value>1</value>
</entry>
<entry>
<key>q</key>
<value>Cairo</value>
</entry>
<entry>
<key>format</key>
<value>xml</value>
</entry>
<entry>
<key>key</key>
<value>wd63kxr294rcgvbynhaf2z4r</value>
</entry>
</parameters>
<URL>
http://api.worldweatheronline.com/free/v1/weather.ashx?q=Cairo&format=xml&num_of_days=1&key=wd63kxr294rcgvbynhaf2z4r
</URL>
<URLPath>/free/v1/weather.ashx</URLPath>
以下是可用于合并两个 xml 的代码片段。
public static void generateDocument(Document root, Document insertDoc, String toPath, String fromPath) {
if (null != root) {
try {
Node element = getNode(insertDoc, fromPath);
Node dest = root.importNode(element, true);
Node node = getNode(root, toPath);
node.insertBefore(dest, null);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public Node getNode(Document doc, String strXpathExpression)
throws ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile(strXpathExpression);
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return node;
}
因此,您的方法是
1. 创建 Soruce.xml 文档 obj(obj1)
2. 创建 test.xml 文档 obj(obj2) 并删除 Main 标签。
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc1 = builder.parse(new File("s1.xml"));
Document doc2 = builder.parse(new File("s2.xml"));
generateDocument(doc1,doc2,"/Main", "Main/source");
作者:黑洞官方问答小能手
链接:http://www.javaheidong.com/blog/article/694202/f760479a9ca2e00e336f/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!