虽然它似乎是一个非常微不足道的问题,但我试图理解XMLReader类,它是成员。鉴于我想退出打印XML声明使用C解析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();
}
的XML文件,但如果我注释掉
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异常是未处理的。 你能解释一下吗?我没有得到全部的图片。
正如WriteStartElement所说的,这是START元素必须在那里。本文可能会给你一些更好的理解。 http://csharp.net-tutorials.com/xml/writing-xml-with-the-xmlwriter-class/ –
谢谢,但我怎么会不打印最初的XML声明。评论这些行不起作用。 – StrugglingCoder