我有下一个简单的xml文件:
<?xml version="1.0" encoding="UTF-8" ?><work><pageSetup paperSize="9" fitToHeight="0" orientation="landscape"></pageSetup></work>
当我运行下一个代码时:
using (XmlReader reader = XmlReader.Create(inFile))
while (reader.Read())
Console.WriteLine("Name = {0}, NodeType = {1}, IsEmptyElement ={2}\n", reader.Name, reader.NodeType, reader.IsEmptyElement);
输出结果为:
Name = xml,NodeType = XmlDeclaration,IsEmptyElement = False
Name = work,NodeType = Element,IsEmptyElement = False
Name = pageSetup,NodeType = Element,IsEmptyElement = False
Name = pageSetup,NodeType = EndElement,IsEmptyElement = False
Name = work,NodeType = EndElement,IsEmptyElement = False
正如你所看到的,PageSetup的IsEmptyElement = False(我不知道为什么......见https://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.isemptyelement.aspx)
但是,如果我使用换行符中的xml(ctrl + alt + shift + b),那就是换行符:
<?xml version="1.0" encoding="UTF-8" ?>
<work>
<pageSetup paperSize="9" fitToHeight="0" orientation="landscape"/>
</work>
运行程序,输出为:
Name = xml,NodeType = XmlDeclaration,IsEmptyElement = False
Name =,NodeType = Whitespace,IsEmptyElement = False
Name = work,NodeType = Element,IsEmptyElement = False
Name =,NodeType = Whitespace,IsEmptyElement = False
Name = pageSetup,NodeType = Element,IsEmptyElement = True
Name =,NodeType = Whitespace,IsEmptyElement = False
Name = work,NodeType = EndElement,IsEmptyElement = False
正如您所见,PageSetup的IsEmptyElement = True
为什么两个xml文件之间有不同的(在pageSetup的IsEmptyElement值中)?
答案 0 :(得分:2)
根据MSDN
,IsEmptyElement
只会报告源文档中的元素是否具有结束元素标记。
在第一种情况下,你有一个结束元素,所以IsEmptyElement
返回false
(虽然元素内容为空),而在第二种情况下,你没有结束标记,这就是为什么你看到{ {1}}设置为IsEmptyElement
。