如何在XML中获取具有列名的数据
本文关键字:数据 获取 XML | 更新日期: 2023-09-27 18:25:55
我有如下的XML文件
<?xml version="1.0" standalone="yes"?>
<ShippersDataSet xmlns="http://www.tempuri.org/ShippersDataSet.xsd">
<Shippers>
<ShipperID>1</ShipperID>
<CompanyName>Speedy Express</CompanyName>
<Phone>(503) 555-9831</Phone>
</Shippers>
<Shippers>
<ShipperID>2</ShipperID>
<CompanyName>United Package</CompanyName>
<Phone>(503) 555-3199</Phone>
</Shippers>
<Shippers>
<ShipperID>3</ShipperID>
<CompanyName>Federal Shipping</CompanyName>
<Phone>(503) 555-9931</Phone>
</Shippers>
</ShippersDataSet>
我有以下XML数据输入:
string XMLpath, string query
查询:
<Query>
<ElementPath> Shippers</ElementPath>
</Query>
我需要添加
如下所示,(我已经在SQL中实现了)与我需要为XML数据添加的方式相同
var list = new List<Myclassdef>();
using (var con = new SqlConnection(Settings.Default.ConnectionString))
{
using (var cmd = new SqlCommand("SELECT ... WHERE Col1=@param1", con))
{
cmd.Parameters.AddWithValue("@param1", "value1");
// ...
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Myclassdef data = new Myclassdef();
data.Data = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
data.Data.Add(reader.GetName(i), reader[i]);
}
list.Add(data);
}
}
}
}
我有以下XML数据输入:
string XMLpath, string query
查询:
<Query><ElementPath> Shippers</ElementPath></Query>
试试这个:
class Program
{
static void Main(string[] args)
{
var list = new List<Myclassdef>();
var query = XDocument
.Parse("<Query><ElementPath> Shippers</ElementPath></Query>");
var doc = XDocument.Parse(File.ReadAllText("xml.xml"));
doc.Descendants(
XName.Get(
query.Root.Value.Trim(),
doc.Root.GetDefaultNamespace().NamespaceName))
.ToList()
.ForEach(e =>
{
var data = new Myclassdef();
data.Data = e
.Elements()
.Select(c => new
{
Name = c.Name.LocalName,
Value = (object)c.Value
})
.ToDictionary(c => c.Name, c => c.Value);
list.Add(data);
});
}
}
您可以使用Linq到XML(命名空间System.XML.Linq):
XDocument document = XDocument.Load(stream); // load the xml into an XDocument from a stream
// select the first of a specific element
IEnumerable<XElement> elements = from shippers in document.Descendants("Shippers") select shippers;
XElement element = (XElement)elements.First().FirstNode;
// loop through all the elements inside that element
foreach (XNode node in elements.First().Nodes())
{
// do something with elements
}