我有一个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>
<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标签内找到数字标签,并使用c#插入子节点(如)。
<profile number = "1">
<profile number = "1">
请帮助!!
答案 0 :(得分: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");
答案 1 :(得分: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();