2015-05-12 56 views
0

我正在尝试执行WCF库应用程序。我坚持要借阅一部书。 我想循环遍历<book>中的所有节点,并且需要编辑一个“userid”节点,它具有与我的函数参数相同的“id”,并尝试做类似的操作。更改选定的XML节点

我的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"); 
+0

什么是你的问题?有些东西没有按照你的预期工作,或者你想让我们猜测? – Alex

+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

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"; 
} 
+0

噢好吧,它的工作,非常感谢! – Pietras