gpt4 book ai didi

c# - 使用 linq to XML 将 xml 文件导入到 datagridview。数据显示不正确

转载 作者:行者123 更新时间:2023-11-30 21:54:03 27 4
gpt4 key购买 nike

我的 XML 文件...

<?xml version="1.0" encoding="UTF-8"?>
<files>
<file type="main">
<document>Report.pdf</document>
<field name="Company">Northwind</field>
<field name="Description">monthly report</field>
<line>
<field name="Description">Error</field>
<field name="Type">4444</field>
</line>
<line>
<field name="Description">Info</field>
<field name="Type">4562</field>
</line>
<line>
<field name="Description">Error</field>
<field name="Type">2135</field>
</line>
<field name="Analyst">Bob</field>
<field name="Manager">Steve</field>
<field name="Dept">Finance</field>
</file>
</files>

我的代码……

XElement xdoc = XElement.Load(@"C:\xmltest\input.xml");

var lines = from item in xdoc.Descendants("line")

select new
{
Description = item.Value,
Type = item.Value

};

dataGridView1.DataSource = lines.ToArray();

这些是我得到的结果......

enter image description here

我想要的结果是...

enter image description here

我认为代码可能有用...

 XElement xdoc = XElement.Load(@"C:\xmltest\input.xml");

var lines = from item in xdoc.Descendants("line")

select new
{
Description = item.Attribute("field").Value,
Type = item.Value

};

dataGridView1.DataSource = lines.ToArray();

我收到的错误是...

"Object reference not set to an instance of an object."

最佳答案

您的代码的问题是:-

item.Attribute("field").Value  //this line

只看您的第一个查询,它返回该结果,因为 item 代表每个 line 节点及其内部存在的相应 field 节点。例如,第一个 item 将是:-

<line>
<field name="Description">Error</field>
<field name="Type">4444</field>
</line>

等等……

现在,在你的第二个查询中,当你说 item.Attribute("field").Value 时,它会抛出 Null reference exception 因为每个 item 不包含属性 field(如您在上面所见),而是一个 元素。所以你应该写 item.Element("field") 来代替。但是,这仍然不会给您预期的结果,因为您希望根据属性值 Descriptionname 获取数据。你可以这样写你的查询:-

var lines = from item in xdoc.Descendants("line")
let fields = item.Elements("field")
select new
{
Description = (string)fields
.FirstOrDefault(n => (string)n.Attribute("name") == "Description"),
Type = (string)fields
.FirstOrDefault(n => (string)n.Attribute("name") == "Type"),
};

解释:

xdoc.Descendants("line") 将获取所有线节点,如上所示,现在在其中我们需要找到所有 fields 节点,以便我们存储它在名为 fields 的变量中。最后,在投影时,我使用了 FirstOrDefault 方法来获取第一个匹配的 name 属性,其值为 DescriptionType并获取它的值(value)。

关于c# - 使用 linq to XML 将 xml 文件导入到 datagridview。数据显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33549462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com