修正し、既存のXMLコンテンツC#
-
26-09-2019 - |
質問
この例でいます。一部の例gived方法を変更す属性 SelectNodes()
または SelectSingleNode()
, その他givedの方法の変更属性 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")
?
解決
から MSDN:"をXPathNavigatorオブジェクトの作成クラスを実装するIXPathNavigableなどのインターフェイスXPathDocumentとXmlDocumentます。 XPathNavigatorで作成したオブジェクトのXPathDocument物を読み取り専用 がXPathNavigatorで作成したオブジェクトのXmlDocument物体を編集することができます。るXPathNavigatorオブジェクトの読み取りまたは編集可能な状態を用いて決定しCanEditのXPathNavigatorクラスです。"
では、最初は使XmlDocumentはXPathDocumentしたい場合は、設定の属性。
方法について、以下に例を示を変更したいXMLデータを用いXPathNavigatorのCreateNavigator方法XmlDocument表示する こちらの.
このビデオをご覧になるとらえる方法があり 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.");
}
}
他のヒント
私はどの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();
}
}
}