Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write NameSpaces in XML

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.

like image 839
Dwcps Avatar asked May 22 '26 12:05

Dwcps


1 Answers

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")
    );
like image 172
Henk Holterman Avatar answered May 24 '26 00:05

Henk Holterman