Reputation: 77
<POW>
<PPE>
<UID>a1</UID>
<ppe1Bool></ppe1Bool>
<ppe1>hello</ppe1>
<ppe2Bool></ppe2Bool>
<ppe2></ppe2>
</PPE>
<PPE>
<UID>a3</UID>
<ppe1Bool></ppe1Bool>
<ppe1>goodbye</ppe1>
<ppe2Bool></ppe2Bool>
<ppe2></ppe2>
</PPE>
</PWO>
How can I insert a new parent with children between the two parent nodes above? So it will read:
<POW>
<PPE>
<UID>a1</UID>
<ppe1Bool></ppe1Bool>
<ppe1>hello</ppe1>
<ppe2Bool></ppe2Bool>
<ppe2></ppe2>
</PPE>
<PPE>
<UID>a2</UID>
<ppe1Bool></ppe1Bool>
<ppe1>new insert</ppe1>
<ppe2Bool></ppe2Bool>
<ppe2></ppe2>
</PPE>
<PPE>
<UID>a3</UID>
<ppe1Bool></ppe1Bool>
<ppe1>goodbye</ppe1>
<ppe2Bool></ppe2Bool>
<ppe2></ppe2>
</PPE>
</PWO>
I have this:
public static void insertRowBeforRowPPE(string strSelection, string strFileName)
{
XmlDocument doc = new XmlDocument();
doc.Load(strFileName);
XmlNodeList lstNode = doc.SelectNodes("PWO/PPE");
foreach (XmlNode node in lstNode)
{
if (node["UID"].InnerText == strSelection)
{
//insert code
}
}
doc.Save(strFileName);
}
strSelection will tell me what child to insert above it's parent....Any help with this will be appreciated.
Upvotes: 2
Views: 115
Reputation: 9261
USING LINQ
To Insert a Node
after a specific Node(insert after a1
)
XDocument xDoc = XDocument.Load("data.xml");
xDoc.Element("POW")
.Elements("PPE").FirstOrDefault(x => x.Element("UID").Value == "a1")
.AddAfterSelf(new XElement("PPE", new XElement("UID", "A")
, new XElement("ppe1Bool")
, new XElement("ppe1", "hello"),
new XElement("ppe2Bool"),
new XElement("ppe2")));
xDoc.Save("mod.xml");
As a side note your xml doesnt seem to be well formed and you need to correct it before using LINQ on it.
Upvotes: 1
Reputation: 32807
Use LINQ2XML
public static void insertRowBeforRowPPE(string strSelection, string strFileName)
{
XElement doc=XElement.Load(strFileName);
foreach(XElement elm in doc.Elements("PPE"))
{
if(elm.Element("UID").Value==strSelection)
elm.AddBeforeSelf(new XElement("PPE",new XElement("UID","a2")));
//adds PPE node having UID element with value a2 just before the required node
}
doc.Save(strFileName);
}
Upvotes: 2