开发者

Linq to XML query creating empty items from XML

开发者 https://www.devze.com 2022-12-20 00:31 出处:网络
Can somebo开发者_开发知识库dy explain why is this xml <?xml version=\"1.0\" encoding=\"utf-8\"?>

Can somebo开发者_开发知识库dy 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:

screenshot http://www.incito.hr/15.2.2010.png


Got it from your updated code sample. When you say

st = XDocument.Load("C:\\storage.xml");

and then

st.Descendants()

your st is the document, not the root element. So when you ask it for its Descendants, you enumerate over 2 XElements - the items node and the one item node that this example have. It is the items 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,

From item In st.Root.Elements("item") 

will enumerate over just the item nodes found as immediate children of the document's root element.

0

精彩评论

暂无评论...
验证码 换一张
取 消