0

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

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • So you're attempting to get nodes within the ```Article``` node and failing to do so? Also, can you post how the ```XML``` is structured? – Brandon Oct 24 '18 at 17:56
  • I you are trying to use linq then use XDocument instead of XmlDocument. – jdweng Oct 25 '18 at 09:15

1 Answers1

1

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();
Matheus Lemos
  • 578
  • 4
  • 13