1

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

这是我的 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>
4

2 回答 2

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);
于 2013-05-01T09:39:06.473 回答
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);
        }
    }
}
于 2013-05-01T09:46:24.347 回答