更改选定的XML节点

时间:2015-05-12 18:53:37

标签: c# xml wcf

我正在尝试做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");

1 个答案:

答案 0 :(得分:1)

在示例中,根元素(或文档元素)是catalog元素,因此XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("catalog/book");将永远不会选择任何内容。当然,您的XML结构包含book等元素,其子元素如iduserid但没有属性,因此您更愿意使用像

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