简体   繁体   中英

C# xmlns can't list nodes

I can't figure it out how to read the data from my xml.

This is my xml file:

<?xml version="1.0" encoding="UTF-8"?>
<ToolSheet xmlns="http://www.mywebpage.hu/ControlDesigner" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <Sites>
    <Site name="Name1" telexCode="N1" />
    <Site name="Name2" telexCode="N2" />
    <Site name="Name3" telexCode="N3" />
    <Site name="Name4" telexCode="N3" />
  </Sites>

</ToolSheet>

Here is my C# code:

XmlDocument doc = new XmlDocument();
doc.Load(_filePath);

List<string> ret = new List<string>();

XmlNodeList value = doc.SelectNodes("ToolSheet/Sites/Site");
foreach (XmlNode node in value)
{
  ret.Add(node.Attributes["name"].Value);
}

I have already tried to use:

nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("mysn", "http://www.mywebpage.hu/ControlDesigner");

//After this read from the xml
XmlNodeList value = doc.SelectNodes("mysn:ToolSheet/Sites/Site");
//And tried much more syntax

I can't list the 'Sites' from my xml. Can someone help me out?

Try following:

        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            List<string> results = ParseXml(FILENAME);
        }
        static List<string> ParseXml(string filename)
        {
            XDocument doc = XDocument.Load(filename);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            return doc.Descendants(ns + "Site").Select(x => (string)x.Attribute("name")).ToList();
        }

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