使用C#读取XML文件 [英] Using C# to read XML file

查看:106
本文介绍了使用C#读取XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我需要阅读的XML文件并从中获取一些数据。

此数据最终会加载到SQL数据库,仍然可以使用需要加载此数据的存储过程。读取此数据的当前方式需要更新,因此我的问题。



我正在尝试编写一个C#程序来读取这些数据。



一些段,记录,无论你想叫什么,都可以存在,甚至可以存在多个或根本不存在。

当我尝试捕获数据时不存在的问题是当前导致问题的原因。



错误就像没有考虑空条件或类似的东西。

I have an XML file I need to read and grab some data from.
This data is eventually loaded to an SQL database and the stored procedures that need to load this data can still be used. The current way this data is read needs to be updated and thus my problem.

I'm trying to write a C# program to read this data.

Some of the "segments", "records" whatever you want to call them can exist and even multiple of them or may not exist at all.
This problem of not being there when I'm trying to capture the data is what is currently causing a problem.

The error is something like not accounting for a null condition or something similar.

推荐答案

另外到Wonde解决方案看看那里 - [XML阅读] [ ^ ]了解各种阅读XML文件的方法。
In addition to Wonde solution take a look there-[XML Read][^] for learn various way to Read XML files.


using System;
using System.Xml;
namespace ReadXml1
{
    class Class1
    {
        static void Main(string[] args)
        {
            // Create an isntance of XmlTextReader and call Read method to read the file
            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
            textReader.Read();
            // If the node has value
            while (textReader.Read())
            {
                // Move to fist element
                textReader.MoveToElement();
                Console.WriteLine("XmlTextReader Properties Test");
                Console.WriteLine("===================");
                // Read this element's properties and display them on console
                Console.WriteLine("Name:" + textReader.Name);
                Console.WriteLine("Base URI:" + textReader.BaseURI);
                Console.WriteLine("Local Name:" + textReader.LocalName);
                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
                Console.WriteLine("Depth:" + textReader.Depth.ToString());
                Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
            }
        }
    }
}


您可以使用 XmlTextReader [ ^ ] .NET类。但是,如果您想要更多地控制它,请查看使用序列化加载对象并将对象保存到XML [ ^ ]



我希望这对你有帮助。
You can read xml file using XmlTextReader[^].NET class. However, if you want more control over it, just take a look at Load and save objects to XML using serialization[^]

I hope this will help you well.


这篇关于使用C#读取XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆