0

I have the following XML string but can't figure out a way to get the values out of an XDocument.

<root>
  <Address>1st Street</Address>
  <City>Denver<City>
</root>

I'm using:

XDocument mydoc = XDocument.Parse(xmlString);

From there, I can't get access "FirstName" and get the value. Any one know how to do this?

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • 1
    Maybe a duplicate of this question? FYI I don't see "FirstName" in the XML you've pasted. http://stackoverflow.com/questions/16221558/how-to-get-value-of-child-node-from-xdocument – Seano666 Mar 03 '16 at 18:24
  • Is your xml missing "FirstName" or do you mean `FirstAttribute` property? – Alexander Derck Mar 03 '16 at 18:28

1 Answers1

1

Without XPath

var xAddress = mydoc.Root.Element("Address");
var xCity = mydoc.Root.Element("City");

var address = xAddress != null ? xAddress.Value : null;
var city = xCity != null ? xCity.Value : null;

You can also use Linq on it:

var fordTrucks = someXml.Root.Elements.Where(elem.Attributes("Type").Value == "Ford");

Or you can transform that into an actual class:

var fordTrucks = someXml.Root.Elements.Where(elem => elem.Attributes("Type").Value == "Ford").Select(elem => {
    return new Truck() {
        Type = Enum.Parse(TypeOf(TruckTypes), elem.Attribute("Type").Value),
        Model = elem.Attribute("Model").Value
    }
});
Ryan Mann
  • 5,178
  • 32
  • 42
  • If Address and City are guaranteed to be in the xml file, then you don't need to check if they are null. However I always do, so that I can always allow for them to not be in the XML file. – Ryan Mann Mar 03 '16 at 18:29
  • 1
    you can also do `var address = (string)mydoc.Root.Element("Address");`. The implementation of the explicit conversion to string in LINQ to XML will return null if the element (or attribute) is not found. Less code to write that way :) – Tim Mar 04 '16 at 22:28