首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Xdoc从XMl文档中抓取属性

使用Xdoc从XMl文档中抓取属性
EN

Stack Overflow用户
提问于 2013-03-29 09:06:09
回答 1查看 313关注 0票数 0

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

代码语言:javascript
复制
<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>

到目前为止我所拥有的一切!

代码语言:javascript
复制
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; }
}
EN

回答 1

Stack Overflow用户

发布于 2013-03-29 09:16:40

<price>是一个元素,但是您访问它时就好像它是一个属性<stock price="..."/>一样。

试试这个:

代码语言:javascript
复制
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));
}

XAttribute转换为double将使用正确的数字XML规则(XmlConvert.ToDouble)。使用double.Parse是不正确的,因为它使用特定于文化的数字格式(例如,在德国,它需要十进制逗号而不是小数点)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15695791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档