poco
poco

Reputation: 3005

c# parse xml with a namespace

I'm having a bit of trouble parsing an xml file with a namespace

the xml file has a line like this

<my:include href="include/myfile.xml"/>

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(file);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("my", "http://www.w3.org/2001/xinclude");

XmlNodeList includeNodeList = xmlDoc.SelectNodes(@"/root/my:include", nsmgr);

I'm used to doing somthing like this but this is not reading how i think it should.. node["href"] is null and no matter what i seem to change cant get

foreach (XmlNode node in includeNodeList)
{
  if (node["href"] != null)
  {                  
    // Save node["href"].Value here                    
  }
}

If i stop it in the debugger i can see node has the info i want in the Outertext. .. i can save outer text and parse it this way but i know there has to be something simple i'm overlooking. Can someone tell me what i need to do to get href value please.

Upvotes: 3

Views: 5750

Answers (2)

rsbarro
rsbarro

Reputation: 27369

Another approach would be to just select the href attributes using XPath:

var includeNodeList = xmlDoc.SelectNodes(@"/root/my:include/@href", nsmgr);
foreach(XmlNode node in includeNodeList)
    node.Value = "new value";

Upvotes: 1

dtb
dtb

Reputation: 217401

The indexer of the XmlNode Class returns the first child element with the given name, not the value of an attribute.

You are looking for the XmlElement.GetAttribute Method:

foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
    if (!string.IsNullOrEmpty(element.GetAttribute("href")))
    {                  
        element.SetAttribute("href", "...");
    }
}

or the XmlElement.GetAttributeNode Method:

foreach (XmlElement element in includeNodeList.OfType<XmlElement>())
{
    XmlAttribute attr = element.GetAttributeNode("href");
    if (attr != null)
    {                  
        attr.Value = "...";
    }
}

Upvotes: 1

Related Questions