Reputation: 161
I want write code in c# which i need to get like this .
<Email version="2.00" xmlns="http://www.portalfiscal.inf.br/nfe"> </Email>
I have tried this but not exact.
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();
and output this code is giving like this
<Email>version=2.00 xmlns=Http://www.portalfiscal.inf.br/nfe</Email>
Upvotes: 2
Views: 251
Reputation: 1499780
Well yes - you're calling WriteString
, which writes text content. Your sample XML contains attributes, so you should be using WriteAttributeString
:
writer.WriteAttributeString("version", "2.00");
writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe");
Do you have to use XmlWriter
though? Personally I'd recommend using LINQ to XML if you possibly can. It's not as suitable for writing enormous documents which XmlWriter
can handle easily, but it's much cleaner when you're just trying to create a simple document of moderate size:
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.
Upvotes: 10
Reputation: 136074
The method you're looking for on XmlTextWriter
is WriteAttributeString
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();
Live example: http://rextester.com/EZU91552
Upvotes: 3