Programing

C #에서 XML 파일을 읽고 구문 분석하는 방법

lottogame 2020. 3. 4. 08:05
반응형

C #에서 XML 파일을 읽고 구문 분석하는 방법


C #에서 XML 파일을 읽고 구문 분석하는 방법


문자열 또는 파일에서 XML을 읽는 XmlDocument

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");

또는

doc.LoadXml("<xml>something</xml>");

그런 다음 아래에서 노드를 찾으십시오.

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");

또는

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}

그런 다음 해당 노드 내부의 텍스트를 다음과 같이 읽으십시오.

string text = node.InnerText;

또는 속성을 읽습니다

string attr = node.Attributes["theattributename"]?.InnerText

Attributes [ "something"]에서 null이 없는지 항상 확인하십시오. 속성이 없으면 null이됩니다.


LINQ to XML 예 :

// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
            where (int)c.Attribute("id") < 4
            select c.Element("firstName").Value + " " +
                   c.Element("lastName").Value;


foreach (string name in query)
{
    Console.WriteLine("Contact's Full Name: {0}", name);
}

참조 : MSDN에서 LINQ to XML


다음은 xml 사이트 맵을 읽기 위해 작성한 응용 프로그램입니다.

using System;
using System.Collections.Generic;
using System.Windows.Forms; 
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;

namespace SiteMapReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter the Location of the file");

            // get the location we want to get the sitemaps from 
            string dirLoc = Console.ReadLine();

            // get all the sitemaps 
            string[] sitemaps = Directory.GetFiles(dirLoc);
            StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);

            // loop through each file 
            foreach (string sitemap in sitemaps)
            {
                try
                {
                    // new xdoc instance 
                    XmlDocument xDoc = new XmlDocument();

                    //load up the xml from the location 
                    xDoc.Load(sitemap);

                    // cycle through each child noed 
                    foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
                    {
                        // first node is the url ... have to go to nexted loc node 
                        foreach (XmlNode locNode in node)
                        {
                            // thereare a couple child nodes here so only take data from node named loc 
                            if (locNode.Name == "loc")
                            {
                                // get the content of the loc node 
                                string loc = locNode.InnerText;

                                // write it to the console so you can see its working 
                                Console.WriteLine(loc + Environment.NewLine);

                                // write it to the file 
                                sw.Write(loc + Environment.NewLine);
                            }
                        }
                    }
                }
                catch { }
            }
            Console.WriteLine("All Done :-)"); 
            Console.ReadLine(); 
        }

        static void readSitemap()
        {
        }
    }
}

페이스트 빈 코드 http://pastebin.com/yK7cSNeY


몇 가지 방법이 있습니다.

  • XmlSerializer. 읽을 대상 스키마가있는 클래스를 사용하십시오. XmlSerializer를 사용하여 클래스의 인스턴스에로드 된 Xml의 데이터를 가져 오십시오.
  • Linq 2 XML
  • XmlTextReader.
  • XmlDocument
  • XPathDocument (읽기 전용 액세스)

다음 중 하나를 수행 할 수 있습니다.

제공된 msdn 페이지에 예제가 있습니다.


Linq에서 XML로.

또한 VB.NET은 C #보다 컴파일러를 통한 XML 구문 분석 지원이 훨씬 우수합니다. 옵션과 욕구가 있다면 확인하십시오.


DataSet을 사용하여 XML 문자열을 읽을 수 있습니다.

var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);

정보를 위해 이것을 게시합니다.


예를 들어 XmlTextReader 클래스를 확인하십시오 .


  public void ReadXmlFile()
    {
        string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
        XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    break;
                case XmlNodeType.Text:
                    columnNames.Add(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    break;
            }
        }
    }

첫 번째 문을 피하고 XmlTextReader 생성자에서 경로 이름을 지정하면됩니다.


원하는 곳에 따라 다른 방법이 있습니다. XmlDocument는 XDocument보다 가벼우지만 문자열에 XML이 포함되어 있는지 최소한으로 확인하려면 정규식이 가장 빠르고 가장 가벼운 선택 일 수 있습니다. 예를 들어, API에 대해 SpecFlow를 사용하여 Smoke Tests를 구현했으며 유효한 XML로 결과 중 하나가 있는지 테스트하고 싶습니다. 그런 다음 정규식을 사용합니다. 그러나이 XML에서 값을 추출 해야하는 경우 더 빠르고 적은 코드로 XDocument로 구문 분석합니다. 또는 큰 XML로 작업해야하는 경우 XmlDocument를 사용합니다 (때로는 1M 줄 정도의 XML로 작업하는 경우도 있음). 그런 다음 줄 단위로 읽을 수도 있습니다. 왜? Visual Studio에서 개인 바이트로 800MB 이상을 열어보십시오. 프로덕션에서도 2GB보다 큰 객체는 없어야합니다. 당신은 twerk와 함께 할 수 있지만해서는 안됩니다. 많은 행이 포함 된 문서를 구문 분석해야하는 경우이 문서는 아마도 CSV 일 것입니다.

XDocument를 사용하여 예제를 볼 수 있기 때문에이 의견을 작성했습니다. XDocument는 큰 문서 나 콘텐츠가 XML에 유효한지 확인하려는 경우에 좋지 않습니다. XML 자체가 의미가 있는지 확인하려면 스키마가 필요합니다.

나는 또한 그 자체에 위의 정보가 필요하다고 생각하기 때문에 제안 된 대답을 하향 조정했습니다. 시간당 10 회 200M의 XML이 유효한 XML인지 확인해야한다고 상상해보십시오. XDocument는 많은 리소스를 낭비합니다.

prasanna venkatesh는 또한 문자열을 데이터 세트에 채울 수 있다고 말하며 유효한 XML도 나타냅니다.

참고 URL : https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c



반응형