【发布时间】:2021-02-24 06:11:15
【问题描述】:
这是我的 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);
}
}
【问题讨论】:
标签: c# xml dom linq-to-xml