在 C# 中修改现有 XML 内容
-
26-09-2019 - |
题
我找到了一些关于这个主题的例子。一些示例给出了修改属性的方法 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")
?
解决方案
从 微软软件定义网络:“XPathNavigator 对象是从实现 IXPathNavigable 接口的类(例如 XPathDocument 和 XmlDocument 类)创建的。 由 XPathDocument 对象创建的 XPathNavigator 对象是只读的 而由 XmlDocument 对象创建的 XPathNavigator 对象可以编辑。XPathNavigator 对象的只读或可编辑状态是使用 XPathNavigator 类的 CanEdit 属性确定的。”
因此,如果要设置属性,首先必须使用 XmlDocument,而不是 XPathDocument。
显示了如何使用 XPathNavigator 使用 XmlDocument 的 CreateNavigator 方法修改 XML 数据的示例 这里.
正如您将从示例中看到的,有一个方法 设定值 在你的 it.Current 对象上。
以下是对代码进行一些细微修改的方法:
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.");
}
}
其他提示
我写了一个扩展方法,提供了 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();
}
}
}
不隶属于 StackOverflow