使用c#解析XML文件
本文关键字:文件 XML 解析 使用 | 更新日期: 2023-09-27 18:11:29
虽然这似乎是一个非常微不足道的问题,我试图理解XMLReader类和它的成员。给定XML文件,我想选择不打印XML声明
static void Main(string[] args)
{
StringBuilder output = new StringBuilder();
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item>test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
Console.WriteLine( output.ToString());
Console.ReadKey();
}
但是如果我注释掉
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
我仍然可以看到XML声明,即
<?xml version='1.0'?>
怎么了?如果我把
注释掉 case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
它说InvalidOperationException未处理。你能解释一下吗?
在代码中设置ws.OmitXmlDeclaration = true;
以省略xml声明。
static void Main(string[] args)
{
StringBuilder output = new StringBuilder();
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item>test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
//case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
Console.WriteLine( output.ToString());
Console.ReadKey();
}
声明的书写是XmlWriter
的一个特点。您可以使用XmlWriterSettings
选择退出。
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
using (XmlWriter writer = XmlWriter.Create(output, settings))
查看所有可用设置的详细信息