0

我有两个 XML 文件要合并到第一个文件的节点中

第一个文件 Toc.xml

<toc>
<item id ="c12">
<english>book1</english>
<french>book1</french>
</title>
</item>
<item id = "part1"/>
<item id = "part2"/>
<item id = "part3"/>
</toc>

每次使用 XML 文件运行转换后都会更新第二个文件(第 1、2、3 部分) 第二个文件:使用 part1.xml 运行转换时

<item id = “part 1”&gt;
<title>
<english>part1</english>
<french>part1</french>
</title></item>

第二个文件:使用 part2.xml 运行转换时

<item id = “part 2”&gt;
<title>
<english>part2</english>
<french>part2</french>
</title>
</item>

结果在 Toc 文件中

  <toc>
  <item id ="c12">
  <english>book1</english>
  <french>book1</french>
  </title>
  </item>
  <item id = "part1">
  <title>
  <english>part1</english>
  <french>part1</french>
  </title>
  </item>
  <item id = "part2">
  <title>
  <english>part2</english>
  <french>part2</french>
  </title>
  </item>
  <item id = "part3">
  <title>
  <english>part3</english>
  <french>part3</french>
  </title>
  </item>
  </toc>

我尝试使用导入节点,但它给了我错误(缺少根元素)和其他错误“要插入的节点来自不同的文档上下文”

这是我尝试过的代码

   XmlDocument temp = new XmlDocument();
    temp.Load("secondfile.xml");
    XmlDocument toc = new XmlDocument();
    toc.Load(toc.xml);
    XmlNodeList toclist = toc.SelectNodes("/toc/item");
    foreach (XmlNode tocnode in toclist) 
    {XmlNodeList tempnodelist = temp.SelectNodes("/item");
    foreach (XmlNode tempnode in tempnodelist)
    { XmlNode importnode = toc.ImportNode(tempnode, true);
    toc.appendNode(importnode, tocnode);
    }}

你说的对。我的问题不清楚。我把 que 改得更具体。我希望这次你会发现它更干净。谢谢你。

4

1 回答 1

0
<item id = “part 1”&gt;
  <title>
    <english>part1</english>
    <french>part1</french>
  </title>
</item>

<toc>
  <item id ="c12">
    <english>book1</english>
    <french>book1</french>  
  </item>
  <item id = "part1"/>
  <item id = "part2"/>
  <item id = "part3"/>
</toc>

答案可能是:

XmlDocument mainDocument = new XmlDocument();
mainDocument.Load("toc.xml");
XmlDocument tempDocument = new XmlDocument();
tempDocument.Load("part1.xml");

XmlNodeList tempList = tempDocument.GetElementsByTagName("item");
string id=tempList[0].GetAttribute("id");//gets the id attribute value

XmlNode mainRoot = mainDocument.DocumentElement; //gets the root node of the main document toc.xml
XmlNodeList mainList = mainRoot.SelectNodes("/toc");
XmlNode itemNode = mainList.Item(0).SelectSingleNode(string.Format("/toc/item[@id=\"" + id + "\"]")); //select the item node according to the id attribute value

XmlNode tempitemNode = tempList.Item(0).SelectSingleNode(string.Format("/toc/item[@id=\"" + id + "\"]/title")); //select the title node of the part1, part2 or part3 files

itemNode.AppendChild(tempitemNode.FirstChild);
itemNode.AppendChild(tempitemNode.LastChild);

mainDocument.Save("toc.xml");

类似的东西

于 2012-08-22T14:47:24.077 回答