简体   繁体   English

使用XMLReader从xml文件读取双

[英]Read double from xml file with XMLReader

I have a simple XML file created with XMLWriter using this code: 我有一个使用以下代码使用XMLWriter创建的简单XML文件:

using (XmlWriter writer = XmlWriter.Create("c:\\temp\\data.xml"))
{

     writer.WriteStartElement("ScaleFactors");  

     writer.WriteStartAttribute("CorrectionFactorX");
     writer.WriteValue(CorrectionFactorX);
     writer.WriteEndAttribute();

     writer.WriteStartAttribute("CorrectionFactorY");
     writer.WriteValue(CorrectionFactorY);
     writer.WriteEndAttribute();

     writer.WriteStartAttribute("CorrectionFactorZ");
     writer.WriteValue(CorrectionFactorZ);
     writer.WriteEndAttribute();

     writer.WriteEndElement();

     writer.Flush();
}

XML file Looks like this: XML文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
    <ScaleFactors CorrectionFactorX="1" 
                  CorrectionFactorY="1" 
                  CorrectionFactorZ="1" />

(CorrectionFactorX/Y/Z are doubles) Now I want to read them back with XMLReader but failed. (CorrectionFactorX / Y / Z是双精度型)现在我想用XMLReader读回它们,但是失败了。 I tried MoveToAttribute/GetAttribute with no success. 我尝试过MoveToAttribute / GetAttribute没有成功。 Any hint and code example is appreciated. 任何提示和代码示例,不胜感激。

Thanks! 谢谢!

If you can use XDoc then 如果可以使用XDoc

void Main()
{
    var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScaleFactors CorrectionFactorX=\"1.31\" CorrectionFactorY=\"1\" CorrectionFactorZ=\"1\" />";
    var xdoc = XDocument.Parse(xml);

    var cfx = Double.Parse(xdoc.Element("ScaleFactors").Attribute("CorrectionFactorX").Value);
    Console.WriteLine (cfx);    
}

If you insist on using XmlReader, then 如果您坚持使用XmlReader,则

void Main()
        {
            var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScaleFactors CorrectionFactorX=\"1.31\" CorrectionFactorY=\"1\" CorrectionFactorZ=\"1\" />";
            using (var reader = XmlReader.Create(new StringReader(xml)))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        Console.WriteLine(reader.Name);
                        var attc = reader.AttributeCount;
                        for (int i = 0; i < attc; i++)
                        {
                            Console.WriteLine(reader.GetAttribute(i));
                        }
                    }
                }
            }
        }

(good example at MSDN on handling different parts of XML, but you're much better off with XDocument ) (在MSDN上处理XML的不同部分的好例子,但是使用XDocument会更好)

using XmlDocument - 使用XmlDocument-

        var xml = new XmlDocument();
        xml.Load("xmlPath");

        var match = xml.DocumentElement.Attributes;
        foreach (XmlAttribute item in match)
        {
            Console.WriteLine(item.Value);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM