我正在尝试从我创建的字符串中读取一些 Xml,但实际上任何 Xml 文件都可以。
我只想像浏览多维矩阵一样浏览 Xml 节点,并最终将它们放入 DataTable 中(将它们放入带有 SqlBulkCopy 的 sql server 中)。我已经在 MSDN 和附近看过了。有人可以简单明了地解释一下吗?
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Xml;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
private static DataTable table = new DataTable();
private static String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Garage>
<Car>
<Name>Ferrari</Name>
<Speed>360km/h</Speed>
<Engine>Ferrari Enzo</Engine>
<Color>Red</Color>
<Year>1999</Year>
</Car>
<Car>
<Name>Maserati</Name>
<Speed>270km/h</Speed>
<Color>Metal Grey</Color>
<Year>2007</Year>
</Car>
<Car>
<Name>Limo</Name>
<Color>Black</Color>
<Engine>Chevrolet</Engine>
<Year>2007</Year>
</Car>
</Garage>";
static void Main(string[] args)
{
Program x = new Program();
XmlReader reader = XmlReader.Create(new StringReader(xmlString));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine(XmlNodeType.Element.ToString());
}
}
}
}
}
我想循环整个事情并得到类似的东西:
名称:法拉利 速度:360公里/小时 发动机:法拉利恩佐
依此类推,你得到了练习。
最佳答案
System.Xml.Linq.XDocument.Parse(string)
会给你一个XDocument
。 XDocument.Root
将为您提供文档的根 XElement
。我认为您会发现这非常容易使用。
您尝试在 .NET 中使用上一代 XML 工具 - 较新的 XDocument
、XElement
等工具更易于访问。
示例代码
using System.Xml.Linq;
...
var root = XDocument.Parse(xmlString).Root;
var cars = root
.ToAll("Car")
.Select(car => new
{
Name = car.ToFirst("Name").Value,
Speed = car.ToAll("Speed").Any() ? car.ToFirst("Speed").Value : null,
Color = car.ToFirst("Color").Value,
Engine = car.ToFirst("Engine").Value,
Year = int.Parse(car.ToFirst("Year").Value)
})
.ToList();
辅助类
public static class XmlHelper
{
public static XNode ReadFrom(Stream stream)
{
using (var xmlReader = XmlReader.Create(stream))
return XDocument.Load(xmlReader);
}
public static void WriteTo(Stream stream, XNode node)
{
using (var xmlWriter = XmlWriter.Create(stream))
node.WriteTo(xmlWriter);
}
public static XElement ToFirst(this XElement ancestor, String descendantLocalName)
{
return ancestor.Descendants().FirstOrDefault(element => element.Name.LocalName == descendantLocalName);
}
public static IEnumerable<XElement> ToAll(this XElement ancestor, String descendantLocalName)
{
return ancestor.Descendants().Where(element => element.Name.LocalName == descendantLocalName);
}
public static string ToAttribute(this XElement element, string name)
{
var attribute = element.Attribute(XName.Get(name));
return attribute != null ? attribute.Value : null;
}
}
关于c# - XmlReader 在 C# 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17033742/