我跟随xml作为对服务的响应,而不想将其解析为键值属性对象。但它不起作用。回应 - 我希望对象的名称为Key prop,value为value of object。
<lst name="industry">
<int name="Accounting">3</int>
<int name="Engineering">0</int>
<int name="Human Resources and Adminstration">0</int>
<int name="Software/IT">0</int>
答案 0 :(得分:4)
您可以使用Linq-Xml选择int
元素和Linq-Objects的ToDictionary()
扩展方法来选择属性作为键,元素的值作为字典中的值:
var xml = @"<lst name=""industry"">
<int name=""Accounting"">3</int>
<int name=""Engineering"">0</int>
<int name=""Human Resources and Adminstration"">0</int>
<int name=""Software/IT"">0</int>
</lst>";
var dict =
XDocument.Parse(xml)
.Root
.Elements("int")
.ToDictionary(xe => xe.Attribute("name").Value, xe => int.Parse(xe.Value));
答案 1 :(得分:1)
您的XML格式不正确。我相信这是你的XML的样子吗?
<lst name="industry">
<int name="Accounting">3</int>
<int name="Engineering">0</int>
<int name="Human Resources and Adminstration">0</int>
<int name="Software/IT">0</int>
</lst>
对于这种情况,你可以做..
XDocument result = XDocument.Load(new StringReader("<lst name=\"industry\">" +
"<int name=\"Accounting\">3</int>" +
"<int name=\"Engineering\">0</int>" +
"<int name=\"Human Resources and Adminstration\">0</int>" +
"<int name=\"Software/IT\">0</int>" +
"</lst>"));
var tmpTable = (from i in result.Descendants("int")
select new
{
Key = i.Attribute("name"),
Value = i.Value
}).ToDictionary(t => t.Key, t => t.Value);