用XDocument替换元素而不是XmlDocument

时间:2011-08-04 02:46:09

标签: c# xml linq-to-xml xmldocument

使用XDocument,如何重写以下代码?此代码使用strValues替换元素值。该元素由strKeysstrXPath = "/root/node/subnode[param1='value1' and param2='value2']"指定。

    public static void ReplaceXmlElement(string strXPath, string[] strKeys, string[] strValues)
    {
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(xmlFile.xml);
        XmlNode xNode = xDoc.SelectSingleNode(strXPath);
        int intTemp = 0;
        foreach (XmlNode node in xNode)
        {
            node.Name.ToString();
            if (node.Name == strKeys[intTemp])
            {
                node.InnerXml = strValues[intTemp];
                intTemp++;
            }
        }
        xDoc.Save(xmlFile.xml);
    }

1 个答案:

答案 0 :(得分:0)

http://msdn.microsoft.com/en-us/library/bb156083.aspx

XElement root = new XElement("Root",
new XElement("Child1", 1),
new XElement("Child2", 2),
new XElement("Child3", 3),
new XElement("Child4", 4),
new XElement("Child5", 5),
new XElement("Child6", 6)
);

XElement el = root.XPathSelectElement("./Child4");