如何从c#中包含XML的字符串读取数据?

时间:2022-09-02 15:24:48

I have found a lot of answer on this question, but they are all trying to convert the string first into file and then trying to parse it using XmlDocument doc = new XmlDocument();

关于这个问题,我已经找到了很多答案,但是他们都试图首先将字符串转换为文件,然后使用XmlDocument doc = new XmlDocument()解析它;

I am newbie in c#. Format of my string is :

我是c#的新手。我的字符串格式是:

<a header = '0'> < row dc = '123' al = '45' msg = '1-st line'/> < row dc = '678' al = '8' msg = 'second-line'/> </a>

I am trying to write the pseudo code to parse it :

我正在写伪代码来解析它:

IF <a header> == 0
Then read from the second line to last line i.e. dc = 678 , al = 8, msg = second-line
ELSE read from the first line to last line i.e.  
  dc = 123 , al = 45, msg = 1-st line
 dc = 678 , al = 8, msg = second-line

After this i have to insert into database. While applying the above condition what will be appropriate solution to this?

在此之后,我必须插入数据库。在应用上述条件时,什么是合适的解决方案?

2 个解决方案

#1


5  

You don't have to save to a file to parse XML.

您不必保存到文件中来解析XML。

var xml = "<a header='0'> <row dc='123' al='45' msg='1-st line'/> <row dc='678' al='8' msg='second-line'/> </a>";
var doc = XElement.Parse(xml);
var list = from x in doc.Descendants("row")
            select new 
            {
                dc = (int)x.Attribute("dc"),
                al = (int)x.Attribute("al"),
                msg = (string)x.Attribute("msg")
            };

This simple sample would give you a list of anonymous objects that you can then easily insert into a DB.

这个简单的示例将为您提供一个匿名对象列表,然后您可以轻松地将其插入到DB中。

#2


0  

Getting started code:

开始代码:

   XmlNode xmlNode = doc.SelectNode("/a");
   int value = xmlNode.Attributes["header"].Value;
   XmlNodes xmlNodes = xmlNode.SelectNodes("./row");
   foreach (XmlNode rowNode in XmlNodes)

#1


5  

You don't have to save to a file to parse XML.

您不必保存到文件中来解析XML。

var xml = "<a header='0'> <row dc='123' al='45' msg='1-st line'/> <row dc='678' al='8' msg='second-line'/> </a>";
var doc = XElement.Parse(xml);
var list = from x in doc.Descendants("row")
            select new 
            {
                dc = (int)x.Attribute("dc"),
                al = (int)x.Attribute("al"),
                msg = (string)x.Attribute("msg")
            };

This simple sample would give you a list of anonymous objects that you can then easily insert into a DB.

这个简单的示例将为您提供一个匿名对象列表,然后您可以轻松地将其插入到DB中。

#2


0  

Getting started code:

开始代码:

   XmlNode xmlNode = doc.SelectNode("/a");
   int value = xmlNode.Attributes["header"].Value;
   XmlNodes xmlNodes = xmlNode.SelectNodes("./row");
   foreach (XmlNode rowNode in XmlNodes)