2013-08-27 15 views
1

我有一個WPF應用程序添加元素,在特定位置的XML中的WPF C#

,我需要插入一個特定的XML位置內的元素標籤。

<Profile> 



    <profile number = "1"> 

     <mode>1</mode> 
     <mode>2</mode> 

    </profile> 

    <profile number = "2"> 

     <mode>1</mode> 
     <mode>2</mode> 

    </profile> 

    <profile number = "3"> 

     <mode>1</mode> 
     <mode>2</mode> 

    </profile> 

</profile> 

在這裏,我想用C#添加模式標籤中的第一個配置文件標籤即

<profile number = "1"> 

我如何找到配置文件標籤上的數字標籤內插入一個子節點到它(像)。

<profile number = "1"> 
<mode> 1 </mode> 
<mode> 2 </mode> 
<mode> 3 </mode> 
</profile> 

請幫忙!!

回答

1

您可以使用XPath來選擇所需的元素和子元素添加到它

string yourxml = "<Profile><profile number = \"1\"><mode>1</mode><mode>2</mode></profile><profile number = \"2\"><mode>1</mode><mode>2</mode></profile><profile number = \"3\"><mode>1</mode><mode>2</mode></profile></Profile>"; 
    XmlDocument doc = new XmlDocument(); 
    doc.LoadXml(yourxml); 

    //Selecting node with number='3' 
    XmlNode profile; 
    XmlElement root = doc.DocumentElement; 
    profile = root.SelectSingleNode("profile[@number = '3']"); 
    XmlElement newChild = doc.CreateElement("mode"); 
    newChild.InnerText = "1"; 
    profile.AppendChild(newChild); 
    doc.Save("file path"); 
0

使用此sample

String xmlString = "<?xml version=\"1.0\"?>"+"<xmlhere>"+ 
    "<somenode>"+ 
    " <child> </child>"+ 
    " <children>1</children>"+ //1 
    " <children>2</children>"+ //2 
    " <children>3</children>"+ // 3, I need to insert it 
    " <children>4</children>"+ //4, I need to insert this second time 
    " <children>5</children>"+ 
    " <children>6</children>"+ 
    " <child> </child>"+ 
    " </somenode>"+ 
    "</xmlhere>"; 

    XElement root = XElement.Parse(xmlString); 
    var childrens = root.Descendants("children").ToArray(); 
    var third = childrens[3]; 
    var fourth = childrens[4]; 
    third.AddBeforeSelf(new XElement("children")); 
    fourth.AddBeforeSelf(new XElement("children")); 

    var updatedchildren = root.Descendants("children").ToArray();