Csharp XmlNode选择单节点错误
我正在尝试删除文本框中的值与 Xml 文件中的值之间的特定匹配项上的元素。这是我的代码,我在以下位置收到错误:
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);
}
}
这是我的 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>"
I am trying to delete an element on a specific match between the value from a textbox and from my Xml file. 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 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>"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
变量
xnode
已指向 URL 元素。只需跳过第二个 xpath 查询:但这意味着您必须更新代码的删除部分,因为 xnode 不指向 MyFavourite 元素:
The varialbe
xnode
points already to the URL element. Just skip the second xpath query:But this means that you have to update the remove part of your code since the xnode does not point to the MyFavourite element: