Humza Munir
Humza Munir

Reputation: 39

XML file format in c# using XmlWriter having namespace and prefixes

Here is the required XML format that I am looking for:

<mf:package 
 xmlns="urn:x-lexisnexis:content:manifest:global:1"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd"
 mf:mf="urn:x-lexisnexis:content:manifest:global:1">

What I am getting is:

<mf:package 
 xmlns="urn:x-lexisnexis:content:manifest:global:1"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
 xmlns:mf="urn:x-lexisnexis:content:manifest:global:1">

The code I am using is:

using (XmlWriter writer = XmlWriter.Create(parentPathPackage + packageID + "_man.xml", settings))
{
    writer.WriteStartElement("mf", "package", "urn:x-lexisnexis:content:manifest:global:1");
    writer.WriteAttributeString("", "xmlns", null, "urn:x-lexisnexis:content:manifest:global:1");
    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
    writer.WriteAttributeString("xsi", "schemaLocation", null, "urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd");

What am I doing wrong here?

Upvotes: 2

Views: 512

Answers (1)

dbc
dbc

Reputation: 116751

Assuming you are writing the root XML element, your desired XML is not well-formed:

<mf:package 
   xmlns="urn:x-lexisnexis:content:manifest:global:1" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
   mf:mf="urn:x-lexisnexis:content:manifest:global:1"> <!--mf:mf is not correct -->

Upload it to https://www.xmlvalidation.com/ and you will get an error,

Errors in the XML document: 1: 250 The prefix "mf" for element "mf:package" is not bound.

Specifically, you define an element <mf:package ... but never associate the mf prefix to a namespace. mf:mf="..." is not the correct way to do that. Instead, a namespace declaration attribute must either be xmlns or begin with xmlns:, so xmlns:mf="..." is the correct way:

<mf:package 
   xmlns="urn:x-lexisnexis:content:manifest:global:1" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
   xmlns:mf="urn:x-lexisnexis:content:manifest:global:1">  <!--Corrected -->

Since this is the XML you are actually getting, XmlWriter generated well-formed XML for you automatically.

Upvotes: 1

Related Questions