-2
<?xml version="1.0" encoding="UTF-8"?>
<meta>
    <field type="xs-string" name="AssetId">TF00000002</field>
    <field type="xs-string" name="Title">TitleOfAsset</field>
</meta>

I have this XML loaded in to a XDocument using the function

XDocument doc = XDocument.Parse(xmlData)

However, I want to be able to retrieve the text fields "TF00000002" and "TitleOfAsset" ... How do I go about doing this?

templateMetaData.assetID = doc
    .Descendants()
    .Where(p => p.Name.LocalName == "AssetId")
    .ToString();

returns:

 System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement] 

Can anyone shine a light on this?

4
  • Doesn't work. is not very precise... can you describe what exactly happens? Commented Jun 27, 2014 at 13:39
  • 1
    "Doesn't work" is far too vague a description. What happened? (Hint: Where returns a sequence, not a single value, and you're currently looking at the element name, not the name attribute). Commented Jun 27, 2014 at 13:39
  • Sorry, yes. It returns "System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement]" instead of the element. Commented Jun 27, 2014 at 13:40
  • possible duplicate of Parsing XML using XDocument Commented Jun 27, 2014 at 14:00

1 Answer 1

0

In your query, you are calling ToString on an IEnumerable<XElement> which will never give you the expected result, instead look for field elements under your Root and get their value:

var values = doc.Root
           .Elements("field")
           .Select(element => (string)element);

If you want to access your values using the name attribute you can use Dictionary:

var values = doc.Root
           .Elements("field")
           .ToDictionary(x => (string)x.Attribute("name"), x => (string)x);

Then you can access the value of AssetId:

var id = values["AssetId"];
Sign up to request clarification or add additional context in comments.

7 Comments

I think element => element.Value would make more sense. Just a suggestion.
This code just tells me that the sequence contains no elements whenever I change "field" to "AssetId" edit: just saw your edit... trying that now
@user3780459 because AssetId is the value of your name attribute. it is not an XElement
OK so now I have this code instead var assetID = doc.Root.Elements("xs-string").ToDictionary(x => (string)x.Attribute("AssetId"), x => (string)x); and it also doesn't return the value of the AssetId. Am I doing something wrong still?
are you kidding with me ? why did you write .Elements("xs-string") ? do you see anything like that in my answer ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.