2

我想用 c# 编写代码,我需要这样。

<Email version="2.00" xmlns="http://www.portalfiscal.inf.br/nfe"> </Email>

我试过这个但不准确。

XmlTextWriter writer = new XmlTextWriter("D:\\nefe.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Email");
writer.WriteString("version=2.00  xmlns=Http://www.portalfiscal.inf.br/nfe");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

并输出这个代码是这样的

 <Email>version=2.00 xmlns=Http://www.portalfiscal.inf.br/nfe</Email> 
4

2 回答 2

11

好吧,是的-您正在调用WriteString,它会写入文本内容。您的示例 XML 包含属性,因此您应该使用WriteAttributeString

writer.WriteAttributeString("version", "2.00");
writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe");

必须使用XmlWriter吗?如果可能的话,我个人建议使用 LINQ to XML 。它不适合编写XmlWriter可以轻松处理的大型文档,但是当您只是尝试创建一个中等大小的简单文档时,它会干净得多:

XNamespace ns = "http://www.portalfiscal.inf.br/nfe";
var doc = new XDocument(new XElement(ns + "Email",
                                     new XAttribute("xmlns", ns.ToString()),
                                     new XAttribute("version", "2.00")));
doc.Save("nefe.xml");

If you do insist on using XmlWriter, you should use a using statement to make sure the output is always closed even if an exception is thrown.

于 2012-12-17T16:32:40.777 回答
4

您正在寻找的方法XmlTextWriterWriteAttributeString

XmlTextWriter writer = new XmlTextWriter("D:\\nefe.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Email");
writer.WriteAttributeString("version","2.00");
writer.WriteAttributeString("xmlns","Http://www.portalfiscal.inf.br/nfe");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

现场示例:http ://rextester.com/EZU91552

于 2012-12-17T16:32:28.993 回答