简体   繁体   English

从XML文件检索值

[英]Retrieve values from XML File

I have Multiple XML Files that look like below 我有多个如下所示的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<schema>
<sp_transaction_id name="sp_transaction_id" value="1" />
<sp_year name="sp_year" value="2015" />
<sp_first_name name="sp_first_name" value="James" />
<sp_gender name="sp_gender" value="Male" />
<sp_date_of_birth name="sp_date_of_birth" value="06-06-1999" />
</schema>

The XML Format i think is in Key-Value Pairs. 我认为XML格式采用键值对形式。 I want to extract these values and store it into a database(SQL Server 2012) table, with the name(eg; sp_year) as Column Name and value(eg; 2015) as the Column value using ASP.NET C#. 我想提取这些值并将其存储到数据库(SQL Server 2012)表中,使用ASP.NET C#将名称(例如sp_year)作为列名,将值(例如2015年)作为列值。 I think i can upload the file and read it like this : 我想我可以上传文件并像这样读取它:

string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string filePath = Server.MapPath("~/Uploads/") + fileName;
FileUpload1.SaveAs(filePath);
string xml = File.ReadAllText(filePath);

But thats pretty much it ( Sorry Im a beginner ). 但这差不多就够了(对不起,我是一个初学者)。 Please Guide me. 请指导我。 Thanks 谢谢

For reading data from an xml file you don't need to upload it.You can give path of xml and read from it.You can use following method to read from xml 要从xml文件中读取数据,您不需要上传它。您可以提供xml的路径并从中读取数据。可以使用以下方法从xml中读取数据

public static XmlDocument LoadXmlDocument(string xmlPath)
    {
        if ((xmlPath == "") || (xmlPath == null) || (!File.Exists(xmlPath)))
            return null;

        StreamReader strreader = new StreamReader(xmlPath);
        string xmlInnerText = strreader.ReadToEnd();
        strreader.Close();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlInnerText);

        return xmlDoc;
    }

For reading data from xml you can use 为了从xml读取数据,您可以使用

XmlDocument xmlDoc = LoadXmlDocument(xmlPath);

XmlNodeList nodes = xmlDoc .SelectNodes("//*");

                foreach (XmlElement node in nodes)
                {
                  .
                  .
                  .
                }

In foreach loop you can get your required values eg sp_year 在foreach循环中,您可以获取所需的值,例如sp_year

The answer below shows how to create an XmlDocument from it. 下面的答案显示了如何从中创建XmlDocument。 I would suggest to use it as a User-Defined class if you know whether Xml schema change. 如果您知道Xml模式是否更改,建议将其用作用户定义的类。 First of all you should create POCO class appropriate to Xml file schema using XmlAnnotations. 首先,您应该使用XmlAnnotations创建适合Xml文件模式的POCO类。 Secondly: Having path of the file: 其次:具有文件路径:

XmlSerializer serializer = new XmlSerializer(typeof(definedclass));
using (FileStream fs = File.Open(pathtofile))
using (XmlReader reader = XmlReader.Create(fs))
{
    var xmlObject = serializer.Deserialize(reader); 
}

xmlObject is now your user-defined class with values from xml. xmlObject现在是您自定义的类,其中包含xml中的值。 Regards, Rafal 问候,拉法尔

You can use the following code to get the key value pairs 您可以使用以下代码获取键值对

XDocument doc = XDocument.Load(filePath);
var schemaElement = doc.Element("schema");
foreach (var xElement in schemaElement.Elements())
    {
        Console.WriteLine(xElement.Attribute("name").Value + ":" + xElement.Attribute("value").Value);
    }

Elements method returns all elements inside schema element. Elements方法返回架构元素内的所有元素。

However I suggest changing xml file to this format, if possible 但是,如果可能,我建议将xml文件更改为这种格式

<?xml version="1.0" encoding="UTF-8"?>
<schema>
<KeyValuePair name="sp_transaction_id" value="1" />
<KeyValuePair name="sp_year" value="2015" />
<KeyValuePair name="sp_first_name" value="James" />
<KeyValuePair name="sp_gender" value="Male" />
<KeyValuePair name="sp_date_of_birth" value="06-06-1999" />
</schema>

You can load the files into an XDocument & then use Linq-To-XML to extract the required information. 您可以将文件加载到XDocument中,然后使用Linq-To-XML提取所需的信息。 The example code below loads all name/value pairs into an array of class : 下面的示例代码将所有名称/值对加载到class数组中:

class MyXMLClass
{
  public String FieldName { get; set; }
  public String Value { get; set; }
}

The code gets all "schema" descendants (just one as it is the top level element), then selects all elements inside the & creates a new class object for each extracting the name & value. 该代码获取所有“模式”后代(因为它是顶层元素而仅一个),然后选择&内的所有元素,为每个提取名称和值的对象创建一个新的类对象。

  XDocument xd = XDocument.Load("test.xml");
  MyXMLClass[] xe =
    xd.Descendants("schema")
      .Elements()
      .Select(n => new MyXMLClass {FieldName = n.Attribute("name").Value, Value = n.Attribute("value").Value})
      .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM