我有以下XML字符串,但无法找到从XDocument中获取值的方法。
<root>
<Address>1st Street</Address>
<City>Denver<City>
</root>
我正在使用:
XDocument mydoc = XDocument.Parse(xmlString);
从那里,我无法访问&#34; FirstName&#34;并获得价值。谁知道怎么做?
答案 0 :(得分:1)
没有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;
您也可以使用Linq:
var fordTrucks = someXml.Root.Elements.Where(elem.Attributes("Type").Value == "Ford");
或者您可以将其转换为实际的类:
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
}
});