[英]Check if xml node has attribute
I have an XML file which is generated from a windows application like below "Repport.xml": 我有一个从Windows应用程序生成的XML文件,例如“ Repport.xml”如下:
<ArrayOfAutoReportXML>
<AutoReportXML ReportName="Report1" ReportID="1" />
<AutoReportXML ReportName="Report2" ReportID="2" />
<AutoReportXML ReportName="Report3" ReportID="3" />
<AutoReportXML ReportName="Report4" ReportID="4" />
<AutoReportXML ReportName="Report5" ReportID="5" />
</ArrayOfAutoReportXML>
I am trying to check if ReportName already exists and i am trying below code to do that: 我正在尝试检查ReportName是否已经存在,并且正在尝试以下代码来做到这一点:
using (FileStream fs = new FileStream("Repport.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
XDocument doc = XDocument.Load(fs);
string attrReportname = (string) doc.Elements("AutoReportXML")
.Where(ox => ox.Attribute("ReportName").Value.ToString() == ReportName)
.FirstOrDefault();
}
And attrReportName
is null
. 并且
attrReportName
为null
。
The issue is that Elements
will only find the immediate child Elements from the current context. 问题在于,
Elements
将仅从当前上下文中找到直接子元素。 The only element returned by doc.Elements()
would be ArrayOfAutoReportXML
. doc.Elements()
返回的唯一元素是ArrayOfAutoReportXML
。
What you need is Descendants
, which traverse all elements in the document. 您需要的是
Descendants
,它遍历文档中的所有元素。
To check if a report exists based on that attribute: 要基于该属性检查报告是否存在:
var reportExists = doc
.Descendants("AutoReportXML")
.Attributes("ReportName")
.Any(x => x.Value == "Report1");
If you needed to check using more than one attribute: 如果您需要使用多个属性进行检查:
var reportExists = doc
.Descendants("AutoReportXML")
.Any(x => (string)x.Attribute("ReportName") == "Report1" &&
(int)x.Attribute("ReportID") == 1);
See this fiddle for a working demo. 请参阅此小提琴以获得有效的演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.