C# 在特定区域中插入节点

C# 在特定区域中插入节点,c#,xml,winforms,C#,Xml,Winforms,strSelection将告诉我要在其父项上方插入哪个子项……对此的任何帮助都将不胜感激。使用LINQ2XML public static void insertRowBeforRowPPE(string strSelection, string strFileName) { XmlDocument doc = new XmlDocument(); doc.Load(strFileName); XmlNodeList lstNode = doc.SelectNodes("PWO/PPE"

strSelection将告诉我要在其父项上方插入哪个子项……对此的任何帮助都将不胜感激。

使用LINQ2XML

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);
}

使用LINQ

在特定节点之后插入
节点
在a1之后插入)


作为旁注,您的xml似乎格式不好,在对其使用LINQ之前需要对其进行更正。

xml中的
PWO
最后应该是
POW
<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>
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);
}
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);
}
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");