I have done the below many times using a xmlDocument approach, but I wanted to use the more powerful linq to xml approach.
However, I seem to have run into a wall.
I am getting data back from a restful API from twillio / crmText.
Here is a link to their site where their docs live:
http://crmtext.com/api/docs
Here is my XML string:
<response op="getcustomerinfo" status="200" message="ok" version="1.0">
<customer>
<totalMsg>3</totalMsg>
<custId>9008281</custId>
<custName></custName>
<timestamp>2015-04-30 16:17:19</timestamp>
<optinStatus>3</optinStatus>
<custMobile>6185551212</custMobile>
<subacct>1st Choice Courier</subacct>
</customer>
</response>
I need to find out the optinStatus. It should return 3.
I am using the below, which return the above xml
XDocument xdoc = XDocument.Parse(result1);
I have tried about 4000 different things, including:
IEnumerable<XElement> otinStatus = from el in xdoc.Elements("customer") select el;
IEnumerable<XElement> otinStatus2 = from el in xdoc.Elements("cusotmer.optinStatus") select el;
IEnumerable<XElement> otinStatus3 = from el in xdoc.Elements("optinStatus") select el;
All of which returns no results.
Please help, I know this is something simple I am missing.
Thank you in advance — Joe
2
Answers
Assuming xDoc being the XDocument. Have you tried..
Retrieve an Element’s Value
Example
Here is a working Fiddle for you. You can see it running live here. The output is
3
.Explanation
Descendents()
is an instance axes method (or just axes in shorthand). It returns anIEnumerable<XElement>
of all matching descendents. On its results, we callSingle()
. It is a Linq method that returns the only element of a sequence. If there is more than one element, it throws an error. We’re left with a singleXElement
. This represent an entire XML element. Since we only want its value not the entire element, we call theValue
property. Bingo, we’re done.A Bit More Detail
Axes come in two kinds:
XElement
,XDocument
, andXNode
classes.With one exception, an axes method returns a collection of type
IEnumerable<T>
. The exception isElement()
, which returns the first matching child object. That what AmatuerDev used and, as in your question, if you are only expecting a single result, it is a just as good if not better approach that isDescendants()
.Retrieve an Attribute Value
Once we have an
XElement
, we can retrieve one of its attributes instead of its value. We do that by calling theAttributes()
method. It returns the matchingXAttribute
. Since we only want the attribute value, we call theValue
property. Voila.General Approach
Using Linq to XML is a two step process.
IEnumerable<T>
result.See Also
Here is some relevant MSDN documentation: