Win phone 7 прочитал XML файл - PullRequest
0 голосов
/ 11 июня 2011

Я сейчас пытаюсь прочитать файл XML и заполнить наблюдаемую коллекцию, но я не вижу, что я делаю здесь неправильно, каждый раз, когда я смотрю в читатель, пустые узлы xml

Этот код загружает XMLфайл в Xelement, и я вижу, что данные верны.

   StreamResourceInfo xml = Application.GetResourceStream(new Uri("/WindowsPhoneDataBoundApplication1;component/Cookies.xml", UriKind.Relative));

   XElement appDataXml;   
   // Get a stream to the XML file which contains the data and load it into the XElement. 
   appDataXml = XElement.Load(xml.Stream);

Похоже, что здесь все идет не так:

    foreach (XNode n in appDataXml.Elements())
    {
        ViewModels.Cookie tempCookie = new ViewModels.Cookie();

        XmlReader reader = n.CreateReader();

        while (reader.Read())
        {
            if (reader.Name == "Name")
            {
                tempCookie.Name = reader.Value.ToString();
            }
        }
        _cookieList.Add(tempCookie);
    }

Если кто-то может указать мне вВ правильном направлении я буду очень благодарен.спасибо.

Редактировать: Вот мой XML-файл

<?xml version="1.0" encoding="utf-8" ?>
  <Cookies>
    <Cookie>
      <Name>Almond Cookies</Name>
      <Description>Cookies With Almonds</Description>
      <Ingredients>
        <Ingredient Name ="Unsalted Butter (Room Temperature)"
                    Amount="1 Cup" 
                    Alternate="2 Sticks"/>
        <Ingredient Name ="Granulated Sugar"
                    Amount="1 Cup" />
        <Ingredient Name ="Large Eggs"
                    Amount="2" />
        <Ingredient Name ="Canned Almond Filling"
                    Amount="1 Cup" />
        <Ingredient Name ="Whole Milk"
                    Amount="1/4 Cup" />
        <Ingredient Name ="All Purpose Flour"
                    Amount="3 Cups" />
        <Ingredient Name ="Baking Soda"
                    Amount="1/2 Teaspoon" />
        <Ingredient Name ="Salt"
                    Amount="1/4 Teaspoon" />
        <Ingredient Name ="Sliced Blanched Almonds"
                    Amount="1/4 Cup" />
      </Ingredients>
      <Temperature>
        <GasMark></GasMark>
        <C></C>
        <F>350</F>
      </Temperature>
    <Duration>15</Duration>
    <Instructions>
      <Line>Preheat the oven to 350F</Line>
      <Line>In a mixing bowl cream butter and sugar till smooth. Add Eggs and blend. Add almond filling and milk and Blend again.</Line>
      <Line>In a seperate bowl mix flour,baking soda and salt. Add to the creamed mixture.</Line>
      <line>Scoop 2 rounded tablespoons of dough and roll to form each cookie. Drop dough onto lightly greased or nonstick cookie sheets, spacing the cookies 2 inches apart. Press sliced almonds onto tops</line>
      <Line>Bake untill cookies are lightly golden and firm to touch, about 15 minutes. Using a spatula transfer cookies to rack and leave to cool.</Line>
    </Instructions>
    <MakesQty>28</MakesQty>
    <ContainsNuts>False</ContainsNuts>
  </Cookie>
</Cookies>

Ответы [ 2 ]

2 голосов
/ 11 июня 2011

Eww, вы смешиваете LINQ to XML с обычными старыми XML-материалами. Выберите один или другой, а не оба. Выберите LINQ to XML. Вы уже начали это. Хотя вы должны использовать XDocument вместо.

var xmlUri = new Uri("/WindowsPhoneDataBoundApplication1;component/Cookies.xml",
                     UriKind.Relative);
var xmlStream = Application.GetResourceStream(xmlUri);

var doc = XDocument.Load(xmlStream);
var newCookies = doc
    .Descendants("Cookie")
    .Select(e =>
        new ViewModels.Cookie
        {
            Name = e.Element("Name").Value,
            // initialize any other values you need here            
            Description = e.Element("Description").Value,
            Ingredients = e
                .Element("Ingredients")
                .Elements("Ingredient")
                .Select(i =>
                    new Ingredient
                    {
                        Name = i.Element("Name").Value,
                        Amount = i.Element("Amount").Value,
                    }),
            Duration = (double)e.Element("Duration"),
            // etc.
        });
_cookieList.AddRange(newCookies); // add the cookies to our existing list
1 голос
/ 11 июня 2011
foreach (XElement cookie in appDataXml.Elements())
{
    ViewModels.Cookie tempCookie = new ViewModels.Cookie();
    tempCookie.Name = cookie.Element("Name").Value;

    _cookieList.Add(tempCookie);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...