简体   繁体   English

从C#中的xml文件获取元素

[英]Get element from xml file in c#

I have an xml file which contains an element . 我有一个包含一个元素的xml文件。 i am storing the content of that xml file as string in csv in one of my projects.i am reading the content of that xml from csv and i want the data of the tag which exists in the content of xml file I tried like this. 我在我的一个项目中将xml文件的内容作为字符串存储在csv中。我正在从csv中读取该xml的内容,并且我想要这样尝试的xml文件内容中存在的标记数据。

XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");

but I am not getting the value of Mail into temp.what should i do? 但是我没有把Mail的价值变成临时的东西,我该怎么办?

GetElementsByTagName returns XmlNodeList . GetElementsByTagName返回XmlNodeList MSDN Reference MSDN参考

// Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");

for (int i=0; i < elemList.Count; i++)
{   
    Console.WriteLine(elemList[i].InnerXml);
}  

Linq solution: Linq解决方案:

var xDoc = XDocument.Load(dataRow["XML"].ToString());

var mailList = xDoc.Descendants("Mail")
                   .Select(x => new
                    {
                        MailID = x.Element("MailID").Value
                    })
                    .ToList();

UPDATE : 更新

XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");

// loop through all retrieved "Mail" elements 
foreach(XmlElement xElem in temp)
{
     string sMailText = xElem.InnerText;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM