0

我有一个 wpf 应用程序,

我需要在特定的 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>

在这里,我想在第一个配置文件标签内添加模式标签,即

<profile number = "1">

我如何在配置文件标签内找到数字标签并使用 c# 在其中插入一个子节点(如)。

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

请帮忙 !!

4

2 回答 2

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");
于 2013-08-27T13:13:17.103 回答
0

使用此示例

 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();
于 2013-08-27T12:47:57.227 回答