在c#中的指定位置添加XML节点

时间:2013-10-07 18:07:28

标签: c# xml

这就是我的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添加内部,然后保存它。那只是在里面创建了新的节点/元素,我将如何再去一个级别,以便我可以在里面添加新的节点/元素?

1 个答案:

答案 0 :(得分: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;
        }     
    } 
}