开发者

C# XDocument, help grabbing elements anonymously

I'm having trouble grabbing elements anonymously. I don't want to call the elements by name. The second foreach statement just grabs the entire section as if it's a single element. How do I cycle through all the va开发者_StackOverflowlues in without calling each one by name? I'm open to doing linq statements, but from every example I've read, I don't see how I can use those without calling each element by name. Thanks for any help!

public class box
{
    public List<Person> People { get; set; } 
}

public class Person
{
    public Dictionary<string, string> data { get; set; } 
}

/*

<outer>
    <xml>
        <person>
          <data>
            <house>Big</house>
            <cell>911</cell>
            <address>NA</address>
          </data>
        </person>
        <person>
          <data>
            <house>Big</house>
            <cell>911</cell>
            <address>NA</address>
          </data>
        </person>
        <person>
          <data>
            <house>Big</house>
            <cell>911</cell>
            <address>NA</address>
          </data>
        </person>
        <person>
          <data>
            <house>Big</house>
            <cell>911</cell>
            <address>NA</address>
          </data>
        </person>
    </xml>
</outer>

*/


this.box.People = new List<Person>();

foreach (var ele in xml.Descendants("person"))
{
    Person somebody = new Person 
    {
        data = new Dictionary<string, string>(),
    };

    foreach (var temp in ele.Descendants("data")) 
    {
        somebody.data.Add(temp.Name.ToString(), temp.Value.ToString()); 
    }

    this.box.People.Add(somebody); 
}


This works (tested) - was just missing the Elements() part:

foreach (var temp in ele.Descendants("data").Elements()) 
{
    somebody.data.Add(temp.Name.ToString(), temp.Value); 
}


This code walks the elements and attributes within an xml document. You don't have to provide a name to the Elements() method.

XDocument xmlDoc = new XDocument();
foreach (XElement element in xmlDoc.Elements()) {
    // .. Do something with the element
    foreach (XAttribute attribute in element.Attributes()) {
        // .. Do something with the attribute
    }
}


foreach (var temp in ele.Descendants("data")) 
{
    foreach( var valueElem in temp.Elements() )
    {
        somebody.data.Add(valueElem.Name.LocalName, valueElem.Value); 
    }
}


If i'm understanding correctly, you may want to look into:

http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜