[英]select multiple values of attributes from xml element which has an attribute matching the certain case c# LINQ
I have XML that looks like 我有看起来像的XML
<?xml version="1.0"?>
<configuration>
<TemplateMapper>
<Template XML="Product.xml" XSLT="sheet.xslt" Keyword="Product" />
<Template XML="Cart.xml" XSLT="Cartsheet.xslt" Keyword="Cart" />
</TemplateMapper>
</configuration>
When I pass in value of attribute Keyword as "product" I want LINQ to return me value of XML and XSLT attributes as Dictionary of string and string. 当我将属性关键字的值作为“产品”传递时,我希望LINQ将XML和XSLT属性的值作为字符串和字符串字典返回给我。
I have so far tried: 到目前为止,我已经尝试过:
var Template="Product"
var dictionary = (from el in xmlElement.Descendants("TemplateMapper")
let xElement = el.Element("Template")
where xElement != null && xElement.Attribute("Keyword").Value == Template
select new
{
XML = el.Attribute("XML").Value,
XSLT= el.Attribute("XSLT").Value
}).ToDictionary(pair => pair.XML, pair => pair.XSLT);
KeyValuePair<string, string> templateValues = dictionary.FirstOrDefault();
It's giving be an error "Object reference not set to instance of an object". 出现错误“对象引用未设置为对象实例”。 Can anyone spot what wrong am I doing? 谁能发现我在做什么错? Helps really appreciated. 帮助真的很感激。
I would try following: 我会尝试以下操作:
var dictionary = (from t in xdoc.Root.Element("TemplateMapper").Elements("Template")
where (string)t.Attribute("Keyword") == Template
select new {
XML = (string)t.Attribute("XML"),
XSLT = (string)t.Attribute("XSLT")
}).ToDictionary(x => x.XML, x => x.XSLT);
(string)XAttribute
does not throw an exception when attribute is not found, so it's better that XAttribute.Value
. 当没有找到属性时, (string)XAttribute
不会引发异常,因此最好使用XAttribute.Value
。
replace your code with this 用这个替换你的代码
var Template="Product"
var dictionary = (from el in xmlElement.Descendants("TemplateMapper")
let xElement = el.Element("Template")
where xElement != null && xElement.Attribute("Keyword").Value == Template
select new
{
XML = xElement .Attribute("XML").Value,
XSLT= xElement .Attribute("XSLT").Value
}).ToDictionary(pair => pair.XML, pair => pair.XSLT);
KeyValuePair<string, string> templateValues = dictionary.FirstOrDefault();
the element you are at currently is xElement not el 您当前所在的元素是xElement not el
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.