3

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.

2
  • Can you post more of your XML, like where the xmlns is declared? Commented Jun 22, 2011 at 1:25
  • Can you show the source XML? With the root and namespace definition. Commented Jun 22, 2011 at 1:25

2 Answers 2

1

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 = "...";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

syntax is a tad off for c#. Don't need the .OfType<XmlElement>() and GetAttributeNode returns a string.. but that did put me down that right path, thanks for the help
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.