简体   繁体   English

从XML文件中获取子节点

[英]Get Child Nodes from an XML File

I have an XML File like below 我有一个XML文件,如下所示

<Attachment>
  <FileName>Perimeter SRS.docx</FileName>
  <FileSize>15572</FileSize>
  <ActivityName>ActivityNamePerimeter SRS.docx</ActivityName>
  <UserAlias>JameelM</UserAlias>
  <DocumentTransferId>7123eb83-d768-4a58-be46-0dfaf1297b97</DocumentTransferId>
  <EngagementName>EAuditEngagementNameNew</EngagementName>
  <Sender>JameelM@orioninc.com</Sender>
</Attachment>

I read these xml file like below 我读了这些xml文件,如下所示

var doc = new XmlDocument();

doc.Load(files);

foreach (XmlElement pointCoord in doc.SelectNodes("/Attachment"))
{

}

I need to get each child node value inside the Attachment node. 我需要在Attachment节点中获取每个子节点值。 How can i get these xml elements from the xml node list? 如何从xml节点列表中获取这些xml元素?

I need to get each child node value inside the Attachment node. 我需要在Attachment节点中获取每个子节点值。

Your question is very unclear, but it looks like it's as simple as: 你的问题很不清楚,但它看起来很简单:

foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
}

After all, in the document you've shown us, the Attachment is the document element. 毕竟,在您向我们展示的文档中, Attachment 文档元素。 No XPath is required. 不需要XPath。

As an aside, if you're using .NET 3.5 or higher, LINQ to XML is a much nicer XML API than the old DOM ( XmlDocument etc) API. 顺便说一句,如果你使用.NET 3.5或更高版本,LINQ到XML是比旧的DOM(一个好得多的 XML API XmlDocument等)的API。

try this 尝试这个

 var data = from item in doc.Descendants("Attachment")
             select new
             {
                  FileName= item.Element("FileName").Value,
                  FileSize= item.Element("FileSize").Value,
                  Sender= item.Element("Sender").Value
              };
 foreach (var p in data)
     Console.WriteLine(p.ToString());
var doc = new XmlDocument();

doc.Load(files);

foreach (XmlElement pointCoord in doc.SelectNodes("/Attachment"))
{
    if(pointCoord!=null)
    {
        var valueOfElement=pointCoord.InnerText;
    }
}

if you want to run conditional logic against the element names (UserAlias, etc) then use the Name property of the XmlElement. 如果要对元素名称(UserAlias等)运行条件逻辑,则使用XmlElement的Name属性。

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

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