根据属性值返回一个元素 [英] Return an Element based on the value of an Attribute
问题描述
我有这个查询,但它似乎并没有执行我想要的操作.
我希望能够返回单个元素和子元素
基于属性ConfigName的值.
XML看起来像这样-
I''ve got this query but it doesn''t seem to do what I''d like.
I want to be able to return a single element and sub-elements
based on the value of attribute ConfigName.
XML looks like this -
<br />
<pre lang="xml"><Controllers><br />
<PLC ConfigName="OP010"><br />
<IPAddress>172.21.1.1</IPAddress><br />
<SubnetMask>255.255.255.0</SubnetMask><br />
<CommSlot>1</CommSlot><br />
<CpuSlot>0</CpuSlot><br />
<ProgName>OP010_ePRESS</ProgName><br />
<CurveTag>Curve</CurveTag><br />
<CommTimeOut>1000</CommTimeOut><br />
<UpdateRate>250</UpdateRate><br />
</PLC><br />
<PLC ConfigName="OP020"><br />
<IPAddress>172.21.1.2</IPAddress><br />
<SubnetMask>255.255.254.0</SubnetMask><br />
<CommSlot>1</CommSlot><br />
<CpuSlot>0</CpuSlot><br />
<ProgName>OP020_ePRESS</ProgName><br />
<CurveTag>Curve</CurveTag><br />
<CommTimeOut>1000</CommTimeOut><br />
<UpdateRate>250</UpdateRate><br />
</PLC><br />
br mode="hold" /></pre>
因此,如果我想查找OP010的数据,我希望它能正常工作,但由于它通过xmlElemList返回所有元素而没有出现-
So, if I want to find the data for OP010, I expected this to work, but it doesn''t appear to as it returns all of the elements via xmlElemList -
<br />
<pre lang="sql">var xmlElemList = from xmlElements in xmlTree.Elements("PLC")<br />
where (string) xmlElements.Attribute("ConfigName").Value == "OP010"<br />
select xmlElements;</pre><br />
有什么想法吗?我希望这返回一个元素.我可以运行查询,然后使用foreach获得想要的内容(如下所示),但是看来我应该只能基于属性值返回想要的元素.
Any thoughts? I would like this to return a single element. I can run the query and then get what I want with a foreach (shown below), but it seems like I should be able to return only the element I want based on the attribute value.
foreach (var xmlElem in xmlElemList.OfType<XElement>())
{
if ((string)xmlElem.FirstAttribute.Value == "OP010")
{
SelectedPLC.ConfigName = (string)xmlElem.FirstAttribute.Value;
SelectedPLC.IPAddress = (string)xmlElem.Element("IPAddress");
SelectedPLC.SubnetMask = (string)xmlElem.Element("SubnetMask");
SelectedPLC.CommSlot = (Int32)xmlElem.Element("CommSlot");
SelectedPLC.CpuSlot = (Int32)xmlElem.Element("CpuSlot");
SelectedPLC.ProgName = (string)xmlElem.Element("ProgName");
SelectedPLC.CurveTag = (string)xmlElem.Element("CurveTag");
SelectedPLC.CommTimeOut = (Int32)xmlElem.Element("CommTimeOut");
SelectedPLC.UpdateRate = (Int32)xmlElem.Element("UpdateRate");
}
推荐答案
默认情况下,LINQ返回集合.如果您需要一次尝试单个 [singleOrDefault [ ^ ],第一 [ FirstOrDefault [
by default LINQ returns collections. If you need a single try single [^], singleOrDefault [^], First[^] or FirstOrDefault[^] Methods
这篇关于根据属性值返回一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!