Linq to XML 查询从 XML 创建空项目
有人可以解释为什么这个 xml
<?xml version="1.0" encoding="utf-8"?>
<items>
<item id="77" cityID="EE12345" cityDatum="15.2.2010. 11:28:35" />
</items>
在使用查询时
Dim c = From items In st.Descendants _
Where items.@id IsNot Nothing _
Select New myStorage With {.id = items.@id, .cityID = items.@cityID, .cityDatum = items.@cityDatum}
storage = c.ToList
会产生包含两个项目的列表(myStorage) - 一个具有所有空(无)属性,第二个具有上面 xml 中看到的值?
我已经通过在 Selectect New myStorage 之前添加解决了该问题
Where items.@id IsNot Nothing _
,但我感觉我不应该这样做。
我已经用 C# 重新创建了它,storage.xml 与上面指定的完全相同。
private void Form1_Load(object sender, EventArgs e)
{
XDocument st;
st = XDocument.Load("C:\\storage.xml");
Object c = from items in st.Descendants()
select new {id = items.Attribute("id"), cityID = items.Attribute("cityID"), cityDatum = items.Attribute("cityDatum")};
}
如果您(有些人无法复制这些结果),请查看以下屏幕截图:
Can somebody explain why is this xml
<?xml version="1.0" encoding="utf-8"?>
<items>
<item id="77" cityID="EE12345" cityDatum="15.2.2010. 11:28:35" />
</items>
when using query
Dim c = From items In st.Descendants _
Where items.@id IsNot Nothing _
Select New myStorage With {.id = items.@id, .cityID = items.@cityID, .cityDatum = items.@cityDatum}
storage = c.ToList
resulting in list(of myStorage) with two items - one with all empty (nothing) properties, second with values seen in xml above?
I've resolved the issue by adding
Where items.@id IsNot Nothing _
before Seletct New myStorage, but I have a feeling that I shouldn't be doing that.
I've recreated this in C#, storage.xml is exactly the same as specified above.
private void Form1_Load(object sender, EventArgs e)
{
XDocument st;
st = XDocument.Load("C:\\storage.xml");
Object c = from items in st.Descendants()
select new {id = items.Attribute("id"), cityID = items.Attribute("cityID"), cityDatum = items.Attribute("cityDatum")};
}
If you, as some can't replicate these results, here's a screenshot:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您更新的代码示例中获取它。当你说
然后
你的
st
是文档,而不是根元素。因此,当您询问其后代
时,您会枚举超过2XElement
-items
节点和一个此示例具有的item
节点。items
节点为您提供“空”项目。有多种方法可以将您自己限制为仅
item
节点,具体取决于您对 xml 结构的确定程度 - 例如,将枚举仅 < code>item 节点作为文档根元素的直接子元素找到。
Got it from your updated code sample. When you say
and then
your
st
is the document, not the root element. So when you ask it for itsDescendants
, you enumerate over 2XElement
s - theitems
node and the oneitem
node that this example have. It is theitems
node that is giving you the 'empty' item.There are numerous ways to restrict yourself to just the
item
nodes, depending on how sure you can be about the structure of your xml - for example,will enumerate over just the
item
nodes found as immediate children of the document's root element.