2012-05-03 5 views
0

これは愚かな質問のように思えるかもしれません。私はmsdnのドキュメントをチェックして、しばらくこのサイトを検索しようとしました。私は残念ながらそれをどうやって実際に理解することができませんでした。xmlnode insert into secondchild ...またはthird?

2番目または3番目の子の後にノードを挿入したいとします。私のXMLの主な内容は孫の中にあり、root.insertを使うと、最初の子の直後に置くことができます。

XML:

<myCourse> 
    <courseName>BEng Mobile and Web Computing</courseName> 
    <courseStructure> 
    <module> 
     <moduleTitle>Programming Methodology</moduleTitle> 
     <credits>15</credits> 
     <semester>1</semester> 
    </module> 
    <module> 
     <moduleTitle>Computer Systems Fundamentals</moduleTitle> 
     <credits>15</credits> 
     <semester>1</semester> 
    </module> 
    </courseStructure> 
</myCourse> 

とコード:

private void buttonCreateNode_Click(object sender, EventArgs e) 
    { 
     // Load the XML document. 
     XmlDocument document = new XmlDocument(); 
     document.Load(@"temp.xml"); 

     // Get the root element. 
     XmlElement root = document.DocumentElement; 

     // Create the new nodes. 
      XmlElement newModule = document.CreateElement("module"); 
      XmlElement newTitle = document.CreateElement("moduleTitle"); 
      XmlElement newCredits = document.CreateElement("credits"); 
      XmlElement newSemester = document.CreateElement("semester"); 
      XmlText title = document.CreateTextNode("ECA411"); 
      XmlText credits = document.CreateTextNode("15"); 
      XmlText semester = document.CreateTextNode("1"); 

      // Insert the elements. 
      newBook.AppendChild(newTitle); 
      newBook.AppendChild(newCredits); 
      newBook.AppendChild(newSemester); 
      newTitle.AppendChild(title); 
      newCredits.AppendChild(credits); 
      newSemester.AppendChild(semester); 
      root.InsertAfter(newModule, root.LastChild); 

     document.Save(@"temp.xml"); 

任意の助けいただければ幸いです。

答えて

3

ご協力ありがとうございます@Mikkelbu。

しかし私はどこで私が達成しようとしていたことを達成することができたのか、私の問題に対する解決策を見出しました。

次のように:

XmlNode parentNode = document.SelectSingleNode("myCourse/courseStructure/level4"); 
      parentNode.InsertBefore(newModule, parentNode.FirstChild); 
0

あなたの問題が正しいと分かっている場合は、モジュールの後に新しいモジュールを挿入したい場合は、タイトルがComputer Systems Fundamentalsのモジュールの後に挿入します。その場合は、挿入の根を変更する必要があります。 だから、私はまた、インスタンスcourseStructureNode、正しい応じてコメントをする変数名rootを変更します

XmlNode root = document.DocumentElement.LastChild; 

にライン

XmlElement root = document.DocumentElement; 

を変更することができます。

ps。コードをコンパイルするには、newBooknewModuleに変更する必要があります。