c# - 在 C# 中修改现有的 XML 内容

标签 c# xml c#-2.0 setattribute selectnodes

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

但我仍然感到困惑,如果我只使用一个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")这样的方法?

最佳答案

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

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

显示了如何使用 XmlDocument 的 CreateNavigator 方法使用 XPathNavigator 修改 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.");
            }
        }

关于c# - 在 C# 中修改现有的 XML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623211/

相关文章:

基于操作系统版本的 C# 条件编译变量

Python ElementTree 对 HTML 实体进行转义

python - 使用 ElementTree 和 Python 覆盖 XML 文件时保留现有命名空间

c# - 如何使用正则表达式从某些文本中提取脚本标签?

c# - 仅在 C# winforms 中的数据网格中单击鼠标后应用的属性

winforms - 如何让文本框只接受数字并用逗号格式化数字?

c# - 读取 XML 和未声明的命名空间

c# - 在 foreach 循环中删除列表中的项目 C#

xml - 如何使用 ASP.NET razor 输出 xml?

c# - 如何格式化运算符 C++ Visual Studio 之间的空间?