我有以下XML结构:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<values>
<bool key="Chapter_1.Boolean1.value">true</bool>
<string key="Chapter_1.Text1.value">abc</string>
<string key="Chapter_1.Text2.value">Inspection done (2)</string>
<number key="Chapter_1.Number1.value">128</number>
<number key="Chapter_1.Number2.value">34539718</number>
<number key="Chapter_1.Number3.value">3</number>
<datetime key="Chapter_2.Chapter_2_1.DateTime1.value">2020-06-02T09:00:00+03:00</datetime>
<datetime key="Chapter_2.Chapter_2_1.DateTime2.value">2016-02-05T00:00:00+02:00</datetime>
<string key="Chapter_3.Text4.value">52</string>
<string key="Chapter_3.Text5.value">22</string>
<number key="Chapter_3.Number6.value">34539718</number>
</values>
以及以下C#代码:
var settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
using (var xmlReader = new XmlTextReader(xmlFilePath))
{
while (xmlReader.Read())
{
var nodeName = xmlReader.Name;
var attrName = xmlReader.GetAttribute("key");
}
}
问题是节点名称为空,并且以下键没有属性:
任何人都知道可能出现什么问题?
答案 0 :(得分:1)
将Xml用于Linq会更容易:
var xml = XDocument.Load(__PATH_TO_XML__);
var values = xml.XPathSelectElements("/values/*")
.Select(x => new
{
Type = x.Name,
Key = x.Attribute("key"),
Value = x.Value
});
答案 1 :(得分:1)
这里的代码运行良好,我能够访问所有xml标签和属性。
也许你感到困惑,因为在每个xmlReader.Read()
它只能读取标签的一部分。因此,要使用键&#34; Chapter_1.Text1.value &#34;, first 读取所有标记,它会读取带有名称{{1}的标记}&key&#34; Chapter_1.Text1.value &#34; ,然后它会读取没有名称的内容,没有属性,但是值&#34; abc&#34; 然后它会使用名称string
读取标记,但没有属性且没有值。
答案 2 :(得分:0)
如果您想要阅读该值,请尝试使用
using (var xmlReader = new XmlTextReader(@"yourxmlfile"))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
var nodeName = xmlReader.Name;
var attrName = xmlReader.GetAttribute("key");
Console.WriteLine(nodeName);
Console.WriteLine(attrName);
}
if (xmlReader.NodeType==XmlNodeType.Text)
{
Console.WriteLine(xmlReader.Value);
}
}
}