虽然循环在读取XML时意外跳转

时间:2013-05-01 09:31:34

标签: c# xml

我正在使用XMLXMLDocument读取XmlNodeReader文件。我不知道while循环会发生什么,它无法运行代码的几个部分。

这是我的C#代码:

    public string TitleXml;
    public string NameXml;
    public string TypeXml;
    public string ValueXml;
    public Guid GuidXml;
    public string DataString;


        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(MyParent.xmlstring);        
        XmlNodeReader xreader = new XmlNodeReader(xdoc);           
        while (xreader.Read())
        {
                    switch (xreader.Name)
                    {
                        case"GUID":
                            GuidXml = Guid.Parse(xreader.ReadInnerXml());
                            //after this break the name of the xreader changes.
                            break;

                        case "Type":
                            TypeXml = xreader.ReadInnerXml();
                            break;

                        case "Name":
                            NameXml = xreader.ReadInnerXml();
                            break;

                        case "Title":
                            TitleXml = xreader.ReadInnerXml();
                            break;

                    }
            }
        xreader.Close();            
        }

这是我的XML:

    <Item>
       <GUID>9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167</GUID>
       <Type>button</Type>
       <Title>Save</Title>
       <Value>submit</Value>
       <Name>btnsave</Name>
       <MaxLen>5</MaxLen>
    </Item>

2 个答案:

答案 0 :(得分:2)

它并没有完全回答你的问题,但是(至少根据我)解决这个问题的简单方法是:

XDocument doc = XDocument.Load("test.xml");

string TitleXml = doc.Descendants("Title").Single().Value;
string NameXml = doc.Descendants("Name").Single().Value;
string TypeXml = doc.Descendants("Type").Single().Value;
string ValueXml = doc.Descendants("Value").Single().Value;
Guid GuidXml = Guid.Parse(doc.Descendants("GUID").Single().Value);

答案 1 :(得分:1)

我也认为你应该使用Linq-to-XML,但是对于你的例子,我会明确列出这些元素,如下所示(可编译的示例程序):

using System;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    internal class Program
    {
        static void Main()
        {
            string xml =
@"<Item>
    <GUID>9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167</GUID>
    <Type>button</Type>
    <Title>Save</Title>
    <Value>submit</Value>
    <Name>btnsave</Name>
    <MaxLen>5</MaxLen>
</Item>";
            XElement elem = XElement.Parse(xml);

            Guid GuidXml = Guid.Parse(elem.Element("GUID").Value);
            Console.WriteLine(GuidXml);

            string TypeXml = elem.Element("Type").Value;
            Console.WriteLine(TypeXml);

            string NameXml = elem.Element("Name").Value;
            Console.WriteLine(NameXml);

            string TitleXml = elem.Element("Title").Value;
            Console.WriteLine(TitleXml);
        }
    }
}