Reputation: 11040
I'm using .net to parse an XML. Below is the XML that needs to be parsed. I need to gather the id from Animal
and info from AnimalName
, AnimalPicture
and AnimalPicture
type.
<AnimalEntry version="2.0">
<Animal id="1">
<Information>
<Type>
Indoor Pet
<Type>
<AvailableTypes> //always only 1 type
<AvailableType>
<Active>
<AnimalName> Rupert</AnimalName>
<AnimalPictures> //Always only 1 picture
<AnimalPicture type="jpg"> random.jpg <AnimalPicture>
</AnimalPictures>
</Active>
</AvailableType>
</AvailableTypes>
<Price>10000</Price>
</Information>
</Animal>
</AnimalEntry>
I can gather the id as follows:
XmlDocument xDoc new XmlDocument();
xDoc.Load(xmlUrl);
XmlNode node = xDoc.DocumentElement.ChildNodes[0];
string id = node.Attributes["id"].Value;
I'm not familiar on how to tackle the nested nodes. Is there a recommended way to get the nested AnimalName, AnimalPicture and OwnerId? Do I need to call a foreach or is there a way I can directly get the node?
Upvotes: 0
Views: 1081
Reputation: 662
using linq to xml, u can try something like this. If you this approach verbose, you can also try xpath using linq how-to-query-linq-to-xml-using-xpath
XElement element = XElement.Parse("Xml data");
foreach (XElement xe in element.Elements(XName.Get("Animal")))
{
string id = xe.Attribute(XName.Get("id")).Value;
var allChildrens = xe.Descendants();
string animalName = allChildrens.FirstOrDefault(x => x.Name == "AnimalName")?.Value;
string animalPicture = allChildrens.FirstOrDefault(x => x.Name == "AnimalPicture")?.Value;
string animalPictureType = allChildrens.FirstOrDefault(x => x.Name == "AnimalPicture")?.Attribute(XName.Get("type"))?.Value;
}
Upvotes: 0
Reputation: 14251
Use linq to xml.
var xml = XElement.Load(xmlUrl);
int id = (int)xml.Element("Animal").Attribute("id");
var active = xml.Element("Animal")
.Element("Information")
.Element("AvailableTypes")
.Element("AvailableType")
.Element("Active");
var animalName = active.Element("AnimalName").Value;
var animalPictureNode = active.Element("AnimalPictures").Element("AnimalPicture");
var animalPicture = animalPictureNode.Value;
var animalPictureType = animalPictureNode.Attribute("type").Value;
Console.WriteLine(id);
Console.WriteLine(animalName);
Console.WriteLine(animalPicture);
Console.WriteLine(animalPictureType);
Open namespace:
using System.Xml.Linq;
Upvotes: 1