如何使用 C# XDocument 读取 xml 文件?
how read a xml file with C# XDocument?
这是我的 XML:
<?xml version="1.0" encoding="utf-8"?>
<solidBodies>
<body>
<name>BLOCK(1)</name>
<density>1200</density>
</body>
<body>
<name>BLOCK(8)</name>
<density>7927,81</density>
</body>
<body>
<name>SPHERE(9)</name>
<density>7192</density>
</body>
</solidBodies>
这是我的代码:
private static void ReadSolidBodyPropertyXml(string solidPropertyXmlFilePath)
{
XDocument xdoc = XDocument.Load(solidPropertyXmlFilePath);
foreach(XElement node in xdoc.Root.Nodes())
{
string name = node.Attribute("name").Value;
int density = Convert.ToInt32(node.Attribute("density").Value);
}
}
问题:我正在尝试获取元素的值,但是我得到了 NullReferenceException
for .Value
。我做错了什么?
我添加我的解决方案:
private static void ReadSolidBodyPropertyXml(string solidPropertyXmlFilePath)
{
XDocument xdoc = XDocument.Load(solidPropertyXmlFilePath);
foreach(XElement node in xdoc.Root.Nodes())
{
string name = node.Element("name").Value;
int density = Convert.ToInt32(node.Element("density").Value);
}
}
您可以尝试使用 LINQ
var xdoc = XDocument.Load(XMLFile);
var items = from item in xdoc.Descendants("solidBodies").Elements("body")
select new
{
name = item.Element("name").Value,
density = item.Element("density").Value
};
foreach (var item in items)
{
Console.WriteLine($"{item.name} {item.density}");
}
输出
BLOCK(1) 1200
BLOCK(8) 7927,81
SPHERE(9) 7192
这是我的 XML:
<?xml version="1.0" encoding="utf-8"?>
<solidBodies>
<body>
<name>BLOCK(1)</name>
<density>1200</density>
</body>
<body>
<name>BLOCK(8)</name>
<density>7927,81</density>
</body>
<body>
<name>SPHERE(9)</name>
<density>7192</density>
</body>
</solidBodies>
这是我的代码:
private static void ReadSolidBodyPropertyXml(string solidPropertyXmlFilePath)
{
XDocument xdoc = XDocument.Load(solidPropertyXmlFilePath);
foreach(XElement node in xdoc.Root.Nodes())
{
string name = node.Attribute("name").Value;
int density = Convert.ToInt32(node.Attribute("density").Value);
}
}
问题:我正在尝试获取元素的值,但是我得到了 NullReferenceException
for .Value
。我做错了什么?
我添加我的解决方案:
private static void ReadSolidBodyPropertyXml(string solidPropertyXmlFilePath)
{
XDocument xdoc = XDocument.Load(solidPropertyXmlFilePath);
foreach(XElement node in xdoc.Root.Nodes())
{
string name = node.Element("name").Value;
int density = Convert.ToInt32(node.Element("density").Value);
}
}
您可以尝试使用 LINQ
var xdoc = XDocument.Load(XMLFile);
var items = from item in xdoc.Descendants("solidBodies").Elements("body")
select new
{
name = item.Element("name").Value,
density = item.Element("density").Value
};
foreach (var item in items)
{
Console.WriteLine($"{item.name} {item.density}");
}
输出
BLOCK(1) 1200
BLOCK(8) 7927,81
SPHERE(9) 7192