C# 从 XML 文件中获取子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14136265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Child Nodes from an XML File
提问by Code-EZ
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>[email protected]</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. How can i get these xml elements from the xml node list?
我需要在附件节点中获取每个子节点值。如何从 xml 节点列表中获取这些 xml 元素?
采纳答案by Jon Skeet
I need to get each child node value inside the Attachment node.
我需要在附件节点中获取每个子节点值。
Your question is very unclear, but it lookslike it's as simple as:
你的问题很不清楚,但看起来很简单:
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
}
After all, in the document you've shown us, the Attachment
isthe document element. No XPath is required.
毕竟,在您向我们展示的文档中,Attachment
是文档元素。不需要 XPath。
As an aside, if you're using .NET 3.5 or higher, LINQ to XML is a muchnicer XML API than the old DOM (XmlDocument
etc) API.
顺便说一句,如果你使用.NET 3.5或更高版本,LINQ到XML是一种多比旧的DOM(更好的XML APIXmlDocument
等)的API。
回答by santosh singh
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());
回答by Faster Solutions
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 属性。