合并XML文件

时间:2017-01-31 06:36:23

标签: xml xml-parsing notepad++

目前我有两个XML文件

one.xml //第一个文件

    <LayoutEntry     name="b1t2mci"           value="$cfg_opt/one"           type=""/>
    <LayoutEntry     name="b1t1ul"            value="$cfg_opt/two"            type=""/>
    <LayoutEntry     name="b1t1fcv"           value="$BattCfgOpt/three"           type=""/>

two.xml //第二个文件

    <cfgOpt>
        <one value="0" />
        <two value="9" />
        <three value="8" />
    </cfgOpt>

我需要将第一个XML中的value属性替换为第二个XML文件中的值。

I.e value =&#34; $ cfg_opt / one&#34;需要替换为值=&#34; 0&#34; 。由于第二个XML文件中的值为零。

由于文件中有1000行,有没有办法让它自动化?

1 个答案:

答案 0 :(得分:0)

不知道自动化它。但是你可以合并xml文件。你可以使用DOM解析器和XPath-参考下面的代码来合并你的文件。在下面的代码中进行必要的更改以实现XML的结构。

public class MergeXmlDemo {
public static void main(String[] args) throws Exception {
// proper error/exception handling omitted for brevity
File file1 = new File("merge1.xml");
File file2 = new File("merge2.xml");
Document doc = merge("/run/host/results", file1, file2);
print(doc);

}

 private static Document merge(String expression,
  File... files) throws Exception {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression compiledExpression = xpath
    .compile(expression);
return merge(compiledExpression, files);

}

  private static Document merge(XPathExpression expression,
  File... files) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    .newInstance();
docBuilderFactory
    .setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = docBuilderFactory
    .newDocumentBuilder();
Document base = docBuilder.parse(files[0]);

Node results = (Node) expression.evaluate(base,
    XPathConstants.NODE);
if (results == null) {
  throw new IOException(files[0]
      + ": expression does not evaluate to node");
}

for (int i = 1; i < files.length; i++) {
  Document merge = docBuilder.parse(files[i]);
  Node nextResults = (Node) expression.evaluate(merge,
      XPathConstants.NODE);
  while (nextResults.hasChildNodes()) {
    Node kid = nextResults.getFirstChild();
    nextResults.removeChild(kid);
    kid = base.importNode(kid, true);
    results.appendChild(kid);
  }
}

return base;

}

  private static void print(Document doc) throws Exception {
TransformerFactory transformerFactory = TransformerFactory
    .newInstance();
Transformer transformer = transformerFactory
    .newTransformer();
DOMSource source = new DOMSource(doc);
Result result = new StreamResult(System.out);
transformer.transform(source, result);

}

}