微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

2 如何解析XML文件或字符串


1 引用XML文件
2 使用XMLReader解析文本字符串
3 使用XMLReader方法读取XML数据

具体代码实现如下:
//初始化一个XML字符串
String xmlString =
                @"<bookstore>
                    <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
                        <title>The Autobiography of Benjamin Franklin</title>
                        <author>
                            <first-name>Benjamin</first-name>
                            <last-name>Franklin</last-name>
                        </author>
                        <price>8.99</price>
                    </book>
                </bookstore>";

ParseXml(xmlString);


static void ParseXml(string xmlString)
{
             
            //创建一个StringBuilder对象用来保存从XML文件中解析出来的文本内容
            StringBuilder output = new StringBuilder();

            创建一个XML读取器
            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
            {
                reader.ReadToFollowing("book");
                reader.MovetoFirstAttribute();
                string genre = reader.Value;
                output.AppendLine("The genre value: " + genre);

                reader.ReadToFollowing("title");
                output.AppendLine("Content of the title element: " + reader.ReadElementContentAsstring());
             }

            
             Console.WriteLine(output);
}

原文地址:https://www.jb51.cc/xml/298475.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。