简体   繁体   中英

Read double from xml file with XMLReader

I have a simple XML file created with XMLWriter using this code:

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 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. I tried MoveToAttribute/GetAttribute with no success. Any hint and code example is appreciated.

Thanks!

If you can use XDoc then

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

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 )

using XmlDocument -

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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