Reputation:
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.
Upvotes: 0
Views: 5816
Reputation: 2896
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
Upvotes: 1
Reputation: 9365
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");
Upvotes: 3