0

最初のファイルのノードにマージしたい 2 つの 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>

2 番目のファイルは、XML ファイルで変換を実行した後、毎回更新されます (パート 1、2、3) 2 番目のファイル:part1.xml で変換を実行中

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

2 番目のファイル: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 に答える