3

I need to generate an XML file using C# class (XmlDocument or XDocument) with the following root element:

<ns1:ConsultaSeqRps xmlns:ns1="http://localhost:8080/WsNFe2/lote" 
    xmlns:tipos="http://localhost:8080/WsNFe2/tp" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://localhost:8080/WsNFe2/lote http://localhost:8080/WsNFe2/xsd/ConsultaSeqRps.xsd">

I've tried various alternatives using setAttribute and XmlNamespaceManager but without success.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Danilo Formagio
  • 189
  • 1
  • 1
  • 7
  • 1
    Show the code you used so we can show you what you did wrong. – John Saunders Mar 18 '14 at 21:40
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Mar 18 '14 at 21:41
  • See if this helps you - may or may not be unrelated - http://stackoverflow.com/questions/8450860/why-does-net-xml-append-an-xlmns-attribute-to-xmlelements-i-add-to-a-document – jdphenix Mar 18 '14 at 21:41

2 Answers2

3

It's pretty straightforward, except maybe for the use of XAttribute to add a named namespace:

XNamespace ns1 = "http://localhost:8080/WsNFe2/lote";
XNamespace tipos = "http://localhost:8080/WsNFe2/tp";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

var doc = new XElement(ns1 + "ConsultaSeqRps",
    new XAttribute(XNamespace.Xmlns + "ns1", ns1), 
    new XAttribute(XNamespace.Xmlns + "tipos", tipos), 
    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
    new XAttribute(xsi + "schemaLocation", 
      "http://localhost:8080/WsNFe2/lote http://localhost:8080/WsNFe2/xsd/ConsultaSeqRps.xsd")
    );
H H
  • 263,252
  • 30
  • 330
  • 514
0

You can take the advantage of LINQ to XML, the following article will help you to Create namespace in c# How to: Create a Document with Namespaces (C#) (LINQ to XML)

Hope that help.

Regards

alnaji
  • 473
  • 3
  • 9