简体   繁体   中英

Get Value by Name of the same Element in XML using C#

I'm having a following XML, in that I'm having two Nodes namely "param" but the Names are different. I need to get the value by Name from the node param. Kindly look at the code

void Main()
{
    string _commentXml = string.Format("<root>{0}{1}</root>"
                             , "<param name=\"Super\">Parameter One</param>"
                             , "<param name=\"Supreme\">Parameter Two</param>");

    XmlDocument _comment = new XmlDocument();
    _comment.LoadXml(_commentXml);


    XElement element = XElement.Load(_comment.DocumentElement.CreateNavigator().ReadSubtree());
    TryGetElementValue(element, "param").Dump();
}

public string TryGetElementValue(XElement parentEl, string elementName, string defaultValue = null)
{
    var foundEl = parentEl.Element(elementName);

    if (foundEl != null)
    {
        var xyz = foundEl.Elements("param");

        if (xyz != null)
        {
            return xyz.First(x => x.Attribute("name").Value == "Super").Value;
        }
    }

    return defaultValue;
}

I can't able to get the value of param with name=Super

I refereed one of the stack-overflow question which is opt for this requirement but I can't.

Referred: XDocument get XML element by the value of its name attribute

Kindly assist me.

Why all this mess?

XDocument has a Descendants method and with linq it's easy:

var xdoc = XDocument.Parse(_commentXml);
var xel = xdoc.Descendants("param")
              .Where(xElement => xElement.Attribute("name")?.Value == "Super");

You can also user XPath.

var element = doc.XPathSelectElement("/path/to/element/I/want");

In your case it would be something like this:

var element = doc.XPathSelectElement("/root/param[@name="Super"]");

Check here for more info: https://stackoverflow.com/a/11224645/1582065

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