Reputation: 2275
I have a wpf application,
where i need to insert a element tag inside a specific xml position.
<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>
Here i want to add mode tag inside the first profile tag i.e.
<profile number = "1">
how do i find the number tag inside the profile tag and insert a child node to it (like ) using c#.
<profile number = "1">
<mode> 1 </mode>
<mode> 2 </mode>
<mode> 3 </mode>
</profile>
Please Help !!
Upvotes: 0
Views: 1008
Reputation: 2610
You can use XPATH to select the required element and add child element to it
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");
Upvotes: 1
Reputation:
Use this 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();
Upvotes: 0