我之前回答过这个问题,但我将 xml 代码的形式更改为更好一点。我是新手,但我有一个问题:以下内容是在运行时编写的。我可以添加所有需要的内容,但如果我想在 PPE/ppe/UID“A3”之前添加元素,我会迷路。以下是我所拥有的:
<?xml version="1.0" encoding="utf-8"?>
<Project>
<Details>
<details>
///....more specific data
</details>
</Details>
<Tools />
<Materials />
<PPE>
<ppe>
<UID>A1</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A1</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
<ppe>
<UID>A3</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A3</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
</PPE>
<Video />
<Links />
</Project>
这是我需要添加的,它需要在 A3 之前
<?xml version="1.0" encoding="utf-8"?>
<Project>
<Details>
<details>
///....more specific data
</details>
</Details>
<Tools />
<Materials />
<PPE>
<ppe>
<UID>A1</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A1</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
//////////////////////////////
<ppe>
<UID>A2</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>New</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
/////////////////////////////
<ppe>
<UID>A3</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A3</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
</PPE>
<Video />
<Links />
</Project>
这是我的代码,我很接近但不完全:
public static void insertRBRowPPE(string strSelection, string strFileName)
{
System.Guid desiredGuid = System.Guid.NewGuid(); //I changed this line to A1..A2..A3 for
//clarity
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFileName);
XmlNode node = xmlDoc.SelectSingleNode("Project/PPE/ppe");
try
{
XElement doc = XElement.Load(strFileName);
foreach (XElement elm in doc.Elements("PPE"))
{
if (node["UID"].InnerText == strSelection)
{
elm.AddBeforeSelf(new XElement("ppe", new XElement("UID", desiredGuid),
new XElement("ppe1Bool", ""), new XElement("ppe1", "New"), new XElement("ppe2Bool", ""),
new XElement("ppe2", "")));
}
}
doc.Save(strFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
所以..错误的结果是这样的:
///xml code etc...
<Materials />
<ppe>////////////////////here but I dont want it here
<UID>A2</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>New</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>//////////////////////////////
<PPE>
<ppe>
<UID>A1</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A1</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
//////////////////////////////
I want it here....
/////////////////////////////
<ppe>
<UID>A3</UID>
<ppe1Bool>true</ppe1Bool>
<ppe1>Test A3</ppe1>
<ppe2Bool>true</ppe2Bool>
<ppe2>....</ppe2>
</ppe>
</PPE>
<Video />
/// xml code etc....
对那里所有的人才有什么帮助吗?谢谢!!