looping through element of XDocument and getting specific attributes

时间:2015-11-12 10:49:19

标签: c# xml linq linq-to-xml

I am currently in the process of rewriting my XmlDocument and XmlElements to XDocument and XElement. I've run into a small problem, I used to simply select a single node ModuleRequests and than loop through it. I thought simple right I'll just rewrite this:

var propertiesRequested = new XmlDocument();
propertiesRequested.LoadXml(propertiesConfiguration);
var requests = propertiesRequested.SelectSingleNode("ModuleRequests");
foreach (XmlNode request in requests)
{
    var propertyValue = request.Attributes["Id"].Value;

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, request.Attributes["Request"].Value);
    }
}

To this:

var propertiesRequested = XDocument.Parse(propertiesConfiguration);
var requests = propertiesRequested.Element("ModuleRequests");

foreach (XNode request in requests)
{
    var propertyValue = request.Attributes["Id"].Value;

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, request.Attributes["Request"].Value);
    }
}

Well needless to say it isn't that easy, then I thought fine i'll make it:

foreach(XNode request in requests.Nodes())

but this gave me even more problems since an XNode does not have an attribute.

As you can probably tell I'm a bit of a novice when it comes to xml reading. I'm hoping someone can help me out. What is the correct way to rewrite from XmlDocument to XDocument

1 个答案:

答案 0 :(得分:1)

You want to use XElement.Elements() to iterate through all child elements of your requests element, then use XElement.Attribute(XName name) to fetch the specified attribute by name.

You might also consider explicitly casting your XAttribute to a string rather than using the Value property, as the former will return null on a missing attribute rather than generating a null reference exception.

Thus:

var propertiesRequested = XDocument.Parse(propertiesConfiguration);
var requests = propertiesRequested.Element("ModuleRequests");
foreach (var request in requests.Elements())
{
    var propertyValue = (string)request.Attribute("Id");

    if (systemProperties.ContainsKey(propertyValue) == false)
    {
        systemProperties.Add(propertyValue, (string)request.Attribute("Request"));
    }
}