在C#中修改现有XML内容

时间:2010-09-02 01:23:14

标签: c# xml c#-2.0 setattribute selectnodes

我找到了一些关于这个主题的例子。一些示例给出了使用SelectNodes()SelectSingleNode()修改属性的方法,其他示例给出了使用someElement.SetAttribute("attribute-name", "new value");修改属性的方法

但如果我只使用XpathNodeItterator it

,我仍然感到困惑的是如何构建关系

假设我定义如下,

System.Xml.XPath.XPathDocument doc = new XPathDocument(xmlFile);
System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator();
System.Xml.XPath.XPathNodeIterator it;

it = nav.Select("/Equipment/Items/SubItmes");
while (it.MoveNext())
{
   name = it.Current.GetAttribute("name ", it.Current.NamespaceURI);
   int vidFromXML = int.Parse(it.Current.GetAttribute("vid", it.Current.NamespaceURI));
   if (vidFromXML = vid)
   { 
    // How can I find the relation between it and element and node? I want to modify name attribute value. 
   }
}

是否有类似it.setAttribute(name, "newValue")的方法?

2 个答案:

答案 0 :(得分:4)

From MSDN:“XPathNavigator对象是从实现IXPathNavigable接口的类创建的,例如XPathDocument和XmlDocument类。 XPathDocument对象创建的XPathNavigator对象是只读的可以编辑由XmlDocument对象创建的XPathNavigator对象.XPathNavigator对象的只读或可编辑状态是使用XPathNavigator类的CanEdit属性确定的。“

因此,首先,如果要设置属性,则必须使用XmlDocument,而不是XPathDocument。

如何使用XPathNavigator使用XmlDocument的CreateNavigator方法修改XML数据的示例显示为here

正如您在示例中看到的那样,it.Current对象上有一个方法 SetValue

以下是您为代码执行此操作的方法,稍作修改:

        int vid = 2;
        var doc = new XmlDocument();
        doc.LoadXml("<Equipment><Items><SubItems  vid=\"1\" name=\"Foo\"/><SubItems vid=\"2\" name=\"Bar\"/></Items></Equipment>");
        var nav = doc.CreateNavigator();

        foreach (XPathNavigator it in nav.Select("/Equipment/Items/SubItems"))
        {
            if(it.MoveToAttribute("vid", it.NamespaceURI)) {
                int vidFromXML = int.Parse(it.Value);                    
                if (vidFromXML == vid)
                {
                    // if(it.MoveToNextAttribute() ... or be more explicit like the following:

                    if (it.MoveToParent() && it.MoveToAttribute("name", it.NamespaceURI))
                    {
                        it.SetValue("Two");
                    } else {
                        throw new XmlException("The name attribute was not found.");
                    }                
                }
            } else {
                    throw new XmlException("The vid attribute was not found.");
            }
        }

答案 1 :(得分:0)

我写了一个扩展方法,为任何SetAttribute提供XPathNavigator方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace My.Shared.Utilities {
    public static class XmlExtensions {
        public static void SetAttribute(this XPathNavigator nav, string localName, string namespaceURI, string value) {
            if (!nav.MoveToAttribute(localName, namespaceURI)) {
                throw new XmlException("Couldn't find attribute '" + localName + "'.");
            }
            nav.SetValue(value);
            nav.MoveToParent();
        }
    }
}