C# 直接读取包含4级以上子节点的xml,同时获取不同深度级别的值
我尝试读取一个包含几乎8级子节点的xml文件,但没有成功。 我尝试使用LINQ、SelectNode、SelectSingleNode,尝试在XMLNodeList上使用哑foreach。 在我的最后一个意图中,我在XMLNodeList上使用这个哑foreach来尝试捕获某些节点的文本或值。 这些节点处于不同的深度级别,但我只能得到序列中的第一个元素,而其余的只重复第一个值 这是我代码的一部分C# 直接读取包含4级以上子节点的xml,同时获取不同深度级别的值,c#,xml,C#,Xml,我尝试读取一个包含几乎8级子节点的xml文件,但没有成功。 我尝试使用LINQ、SelectNode、SelectSingleNode,尝试在XMLNodeList上使用哑foreach。 在我的最后一个意图中,我在XMLNodeList上使用这个哑foreach来尝试捕获某些节点的文本或值。 这些节点处于不同的深度级别,但我只能得到序列中的第一个元素,而其余的只重复第一个值 这是我代码的一部分 XmlDocument xDocXML = new XmlDocument(); xDocXML.L
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 });
}
在不知道XML是什么样子的情况下,我建议创建一个类来表示XML文件,然后使用序列化。使用此解决方案,您可以拥有多个级别,并让框架处理它们 请勾选此项,例如: 您还可以使用外部工具生成POCO类,例如: 链接解决方案中的示例代码: 表示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; }
}
阅读代码:
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();
那么您正试图获取
文章
节点中的节点,但没有成功?另外,您能否发布XML
的结构?如果您试图使用linq,请使用XDocument而不是XmlDocument。@AleAlvaradoLuz如果它解决了您的问题,请将标记作为解决方案