[英]Csharp XmlNode select single node error
I am trying to delete an element on a specific match between the value from a textbox and from my Xml file. 我正在尝试删除文本框和Xml文件中值之间特定匹配的元素。 This is my code and I am getting an error in: 这是我的代码,但出现错误:
string x = xnode.SelectSingleNode("Url").InnerText.ToString();
XmlDocument favourites = new XmlDocument();
favourites.Load("Favourites.xml");
foreach (XmlNode xnode in favourites.SelectNodes("Favourite/MyFavourite/Url"))
{
string x = xnode.SelectSingleNode("Url").InnerText.ToString();
if (x == Url)
{
// xnode.ParentNode.ReplaceChild(newchild,oldChild);
xnode.ParentNode.RemoveChild(xnode);
}
}
this is my xml: 这是我的xml:
"<?xml version="1.0" encoding="utf-8"?>
<Favourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.yahoo.com</Url>
</MyFavourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.gmail.com</Url>
</MyFavourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.naji.com</Url>
</MyFavourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.yahoo.com</Url>
</MyFavourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.yahoo.com</Url>
</MyFavourite>
<MyFavourite>
<name>Haider</name>
<Url>http://www.yahoo.com</Url>
</MyFavourite>
</Favourite>"
The varialbe xnode
points already to the URL element. varialbe xnode
已经指向URL元素。 Just skip the second xpath query: 只需跳过第二个xpath查询:
string x = xnode.InnerText.ToString();
But this means that you have to update the remove part of your code since the xnode does not point to the MyFavourite element: 但是,这意味着你需要更新你的代码的删除部分,因为xnode不指向MyFavourite元素:
XmlNode favoriteNode = xnode.ParentNode;
favoriteNode.ParentNode.RemoveChild(favoriteNode);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.