在此XML中更新XElement(更新元素Pen的itemNumber值)的最佳方法是什么?
<?xml version="1.0" encoding="utf-8"?>
<MyStore>
<Category>
<itemName>Pen</itemName>
<itemNumber>12</itemNumber>
</Category>
<Category>
<itemName>Paper</itemName>
<itemNumber>23</itemNumber>
</Category>
</MyStore>
答案 0 :(得分:12)
XDocument doc;
...
XElement penItemValue = doc
.Elements("MyStore")
.Elements("Category")
.Elements("itemName")
.Single(itemName => itemName.Value == "Pen")
.Parent
.Element("itemValue");
penItemValue.Value = "123";
答案 1 :(得分:3)
你可以找到它并使用LinqToXml更新它:
XElement root = XElement.Load("myXml.xml");
var penCategory = from category in root.Descendants("Category")
where category.Element("itemName") != null
&& category.Element("itemName").Value == "Pen"
select category;
penCategory.Element("itemName").Value = updatedValue;
答案 2 :(得分:1)
我会使用Xpath找到你要找的元素,然后直接操作它。
对于XPath,//Category[itemName='Pen']/itemNumber
之类的东西会找到该元素
for more on Xpath see
以下(非常基本的)代码段以单声道
为我工作using System.Xml;
namespace test
{
class myclass
{
public static void Main(string[] argv)
{
XmlTextReader reader = new XmlTextReader(argv[0]);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode myNode;
XmlElement root = doc.DocumentElement;
myNode = root.SelectSingleNode("//Category[itemName='Pen']/itemNumber");
myNode.InnerText = "18";
doc.Save(argv[1]);
}
}
}
答案 3 :(得分:0)
使用XPath(大多数XML开发人员都熟悉):
var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<MyStore>
<Category>
<itemName>Pen</itemName>
<itemNumber>12</itemNumber>
</Category>
<Category>
<itemName>Paper</itemName>
<itemNumber>23</itemNumber>
</Category>
</MyStore>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var nav = doc.CreateNavigator();
var iter = nav.Select("/MyStore/Category[itemName='Pen']/itemNumber");
iter.MoveNext();
iter.Current.SetValue("42");