1

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

但是我仍然很困惑,如果我只使用 a ,如何建立关系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")

4

2 回答 2

4

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

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

此处显示了如何通过 XmlDocument 的 CreateNavigator 方法使用 XPathNavigator 修改 XML 数据的示例。

正如您将从示例中看到的那样,您的 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.");
            }
        }
于 2010-09-02T01:46:36.080 回答
0

我写了一个扩展方法,它SetAttribute为 any 提供了一个方法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();
        }
    }
}
于 2013-01-29T10:58:33.110 回答