简体   繁体   中英

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. 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>"

The varialbe xnode points already to the URL element. Just skip the second xpath query:

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:

XmlNode favoriteNode = xnode.ParentNode;
favoriteNode.ParentNode.RemoveChild(favoriteNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM