更改选定的 XML 个节点

Change selected XML Node

我正在尝试做 WCF 库应用程序。我坚持借书部分。 我想遍历 <book> 中的所有节点并需要编辑一个 "userid" 节点,它有一个 "id" 与我的函数的参数相同,试图做类似的事情。

我的XML结构

<catalog>
  <book>
    <id>bk101</id>
    <title>XML Developer's Guide</title>
    <author>Gambardella, Matthew</author>
    <userid>789</userid>
  </book>
  <book>
    <id>bk102</id>
    <title>Midnight Rain</title>
    <author>Ralls, Kim</author>
    <userid>720</userid>
  </book>
  <book>
    <id>bk103</id>
    <title>Testowa</title>
    <author>TESTTT, test</author>
    <userid>666</userid>
  </book>
  <book>
    <id>bk105</id>
    <title>qwertyuiop</title>
    <author>Qwe, Asd</author>
    <userid></userid>
  </book>
</catalog>

借书功能(目前,只是尝试在那里设置硬编码值)

public void borrowBook(string s)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("SampleDB.xml");
    XmlElement root = doc.DocumentElement;
    XmlNodeList nodes = root.SelectNodes("catalog/book");
    foreach (XmlNode node in nodes)
    {
        if (node.Attributes["id"].Value.Equals(s))
        {
            node.Attributes["userid"].Value = "new value";
        }
    }
    db.Save("SampleDB.xml");
}

客户端部分:

BookServiceReference.BookServiceClient client = 
new BookServiceReference.BookServiceClient();
BookServiceReference.Book[] x = client.borrowBook("bk101");

在示例中,根元素(或文档元素)是 catalog 元素,因此 XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("catalog/book"); 永远不会 select 任何东西。当然,您的 XML 结构包含 book 之类的元素以及 iduserid 之类的子元素,但没有属性,因此您宁愿使用

之类的代码
foreach (XmlElement book in doc.SelectNodes(string.Format("catalog/book[id = '{0}']", s))
{
  book["userid"].InnerText = "new value";
}