Reputation: 1
I try to read an xml file with almost 8 leves of child nodes but without succsses. I try using LINQ, SelectNode, SelectSingleNode, try to use a dumb foreach over XMLNodeList. In my last intent I use this dumb foreach over the XMLNodeList to try to catch the text or value of some nodes. These nodes are in diferents levels of deep but I can get onle the first element in sequesnse but the rest only repeat the firs value.
This is part of my code.
XmlDocument xDocXML = new XmlDocument();
xDocXML.Load(file_name);//file_name is a string with the full path of the file
XmlNodeList Article = xDocXML.SelectNodes("/ArticleSet/Article/Document"); //We get the Document of the article
foreach(XmlNode n in Article)
{
spmid = n["ID"].InnerText;
liga = string.Concat(TestString1, spmid);
//Test 1
//stitle = n.SelectSingleNode("//Article/ArticleTitle").InnerText;
//Test 2
//stitle = n["//Article/ArticleTitle"].InnerText;
XmlNode titles = n.SelectSingleNode("//Article/ArticleTitle");
stitle = titles.InnerText;//This line only work once and it repeat in all xmlnodes read
camposcuenta = camposcuenta + 1;
dt_abstractdb.Rows.Add(new Object[] { camposcuenta.ToString(), spmid, stitle, sresum, liga, ligaPDF, ligadoi });
}
Any suggestion over this
Upvotes: 0
Views: 288
Reputation: 628
Without knowing what your XML looks like, I would recomend creating a class to represent your XML file and then use serialization. With this solution you can have multiple levels and let the Framework handle them.
Check this for example: How to Deserialize XML document
You can also use an external tool to generate your POCO classes, for exemple: https://xmltocsharp.azurewebsites.net/
Example code from the link's solution:
Classes to represent your XML:
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement("StockNumber")]
public string StockNumber { get; set; }
[System.Xml.Serialization.XmlElement("Make")]
public string Make { get; set; }
[System.Xml.Serialization.XmlElement("Model")]
public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Car { get; set; }
}
Reading code:
CarCollection cars = null;
string path = "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
Upvotes: 1