0

很难从我的 XML 中检索属性。我需要获取这个属性,然后发送和存储它。我不能让它装扮属性。:( 只需要属性方面的帮助。

<portfolios>
  <portfolio>
    <id>00001</id>
    <investment ticker="ASD">
      <shares>20</shares>
      <price>42.50</price>
    </investment>
  </portfolio>

  <pricedata days="4">
    <stock ticker="ASD">
      <price value="42.50"/>
      <price value="43.50"/>
      <price value="39.00"/>
      <price value="45.00"/>
    </stock>
  </pricedata>
</portfolios>

我到目前为止所拥有的!

public bool readXmlData(String filename)
{
    XDocument document = XDocument.Load(filename);

    foreach (XElement portfolio in document.Descendants("portfolio"))
        {
            XElement id = portfolio.Element("id");
            string id2 = id != null ? id.Value : string.Empty;
            portList.Add(new SmallPortfolio(id2));

            XAttribute ticker = portfolio.Attribute("investment");

            foreach(XElement investment in document.Descendants("investment"))
            {
                XElement shares = investment.Element("shares");
                XElement price =  investment.Element("price");

                temp.Add(new Investment(

                ticker != null ? ticker.Value : string.Empty,
                shares != null ? int.Parse(shares.Value) : default(int),
                price != null ? double.Parse(shares.Value) : default(double)
                ));
            }
        }

    foreach (XElement stock in document.Descendants("pricedata"))
    {
        XAttribute tick = stock.Attribute("stock");
        List<Double> pricetemp2 = new List<Double>();
        foreach (XElement price in document.Descendants("stock"))
        {
            XAttribute value = price.Attribute("price");
            pricetemp2.Add(value.Value);
        }
        groupList.Add(new PriceGroup(tick,pricetemp2));
    }
    return true;
}
public List<SmallPortfolio> getPortfolioList() { return null; }
public List<PriceGroup> getPriceList() { return null; }
}
4

1 回答 1

1

<price> is an element, but you are accessing it as if it was an attribute <stock price="..."/>.

Try this:

foreach (XElement stock in document.Descendants("stock"))
{
    string ticker = (string)stock.Attribute("ticker");
    List<Double> pricetemp2 = new List<Double>();
    foreach (XElement price in stock.Descendants("price"))
    {
        double value = (double)price.Attribute("value");
        pricetemp2.Add(value);
    }
    groupList.Add(new PriceGroup(ticker, pricetemp2));
}

Casting XAttribute to double will use the proper XML rules for numbers (XmlConvert.ToDouble). Using double.Parse is incorrect as it uses culture-specific number formatting (e.g. in Germany it expects a decimal comma instead of a decimal point).

于 2013-03-29T01:16:40.057 回答