无法从XML字符串中读取某些元素

时间:2016-03-08 08:59:07

标签: c# xml

我有以下XML String(XMLText):

<?xml version="1.0" encoding="utf-8" ?>
<RateSheet>
    <rate category="children" date="2016-04-21">
    <value>1.375</value> 
    </rate>

    <rate category="music" date="2016-05-01">
    <value>2.475</value>                                   
    </rate>
</RateSheet>

我需要从该XML中读取以下信息:类别,日期和值

我可以阅读类别和日期 - 但我无法读取数据值

我有这段代码:

using (XmlReader reader= XmlReader.Create(new StringReader(XMLText)))
{
    while (reader.ReadToFollowing("rate"))
    {

        Rate rate = new Rate();

        reader.MoveToFirstAttribute();
        rate.Category = reader.Value;  //text of current Node   : Catagory

        //*************************************************************************************

        reader.MoveToNextAttribute();  //text of current Node  : Date
        DateTime myDate;

        if ( DateTime.TryParse( reader.Value, out myDate) )     
        {
         rate.Date =  myDate;                                   
        }

        //*************************************************************************************

        reader.ReadToFollowing("value");   //should be 1.375 or 2.475 - but is always empty ("")

        Console.WriteLine("value Element=" + reader.Value); //test: reader.Value does not the data


        decimal myValue;                                    

        if (Decimal.TryParse(reader.Value, out myValue))
        {
            rate.Value = myValue;
        }
        else
        {
            rate.Value = -1;   // this is what happens because reader.value == ""
        }

        //return collection with result
        myRates.Add(rate);



    }
}

3 个答案:

答案 0 :(得分:3)

您可以执行简单的LinqXml

var myrates = doc.Descendants("rate")
    .Select(r=> new Rate() {
        Category = r.Attribute("category").Value,
        Date =  DateTime.ParseExact(r.Attribute("date").Value,"yyyy-MM-dd", null),
        Value = double.Parse(r.Element("value").Value),

    }).ToList();

工作Demo

答案 1 :(得分:0)

以下是您的代码遗漏的内容。之后

reader.ReadToFollowing("value");

您需要添加以下行:

reader.Read();

之后它是“读者。价值;”将返回&lt; value&gt;内的文字。 或者,您可以使用DOM和xpath代替linq或Streamreader:

XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
List<Rate> rates = new List<Rate>();

XmlNodeList nodes = doc.SelectNodes("//rate");

foreach(XmlNode x in nodes)
{
    Rate r = new Rate();
    r.Category = x.Attributes["category"].Value;
    r.Date = DateTime.ParseExact(x.Attributes["date"].Value,"yyyy-MM-dd", null)x.Attributes["category"].Value;
    r.Value = double.Parse(x.SelectSingleNode("./value").InnerText));
    rates.Add(r);
}

答案 2 :(得分:0)

我喜欢使用XmlReader和Linq的组合

equals