Reputation: 2157
I have an XDocument new_doc which has the following XML like
<lab:lab uri="https://bh03.org/api/lb/3" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:lab="http://ge.com/ri/lab">
<name>GTech</name>
<udf:field type="String" name="Account ID">gt</udf:field>
</lab:lab>
With the below code I am trying to get the Value for Account ID
XNamespace ns = "http://ge.com/ri/userdefined";
accountID = new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;
But how do I check if the <udf:field type="String" name="Account ID">gt</udf:field>
is present before getting the value for the Account ID. Because sometimes the XML might be something like below
<lab:lab uri="https://bh03.org/api/lb/3" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:lab="http://ge.com/ri/lab">
<name>GTech</name>
</lab:lab>
Upvotes: 1
Views: 48
Reputation: 116168
You can use XPath and check if field is null or not..
var nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("udf", "http://ge.com/ri/userdefined");
var xDoc = XDocument.Load(filename);
var field = xDoc.XPathSelectElement("//udf:field[@name]", nsmgr);
if(field != null)
{
var name = field.Attribute("name");
}
PS: In fact //udf:field
is enough. //udf:field[@name]
checks also the existence of name attribute. A more restricted version of it can be //udf:field[@name='Account ID']
Upvotes: 1