0

这就是我的 xml 的样子:

<Runners>
<Runner>
    <RunnersBadge>
    123
    </RunnersBadge>
    <Times>
    </Times>
</Runner>

<Runner>
    <RunnersBadge>
    456
    </RunnersBadge>
    <Times>
    </Times>
</Runner>   

我可以使用以下代码找到特定的跑步者,例如 123:

//loadxml
string findrunner = "123";
XmlNodelist nodelist = "xmldocument".SelectNodes("Runners\Runner")

foreach(XmlNode node in nodelist)
{
 if ( node["RunnersBadge"].InnerText.Equals(findrunner)
{
 //This is how far I get, I can find the runner because if I put a value inside times
 //and output it in a message box, it is showing the proper one for runner 123.
}

我将如何在内部添加一个名为的节点,以便 xml 看起来像这样:

<Runners>
<Runner>
    <RunnersBadge>
    123
    </RunnersBadge>
    <Times>
        <LapTime>
        </LapTime>
        <LapTime>
        </LapTime>
    </Times>
</Runner>

<Runner>
    <RunnersBadge>
    456
    </RunnersBadge>
    <Times>
    </Times>
</Runner>   

我可以使用 CreateElement("LapTime") 然后 ApphendChild 在里面添加,然后保存它。那只是在里面创建了新的节点/元素,我将如何再上一层以便我可以在里面添加新的节点/元素?

4

1 回答 1

0

以下代码应根据需要将新节点添加到两个级别...

string message = "<Insert XML Here>";
string findrunner = "123";
XmlDocument document = new XmlDocument();
document.LoadXml(message);
XmlNodeList nodelist = document.SelectNodes("//Runner");

foreach (XmlNode node in nodelist)
{
    foreach (XmlNode child in node.ChildNodes)
    {
        if (child.Name == "RunnersBadge" && child.InnerText.Equals(findrunner))
        {
            XmlNode Times = null;
            XmlNode LapTime = null;
            if ((Times = node.SelectSingleNode("//Times")) == null)
            {
                Times = document.CreateNode(XmlNodeType.Element, "Times", "");
                node.AppendChild(Times);
            }

            LapTime = document.CreateNode(XmlNodeType.Element, "LapTime", "");
            LapTime.InnerText = ""; // Set Value Here
            Times.AppendChild(LapTime);
            break;
        }     
    } 
}
于 2013-10-07T18:35:26.627 回答