Home > other >  c# xml replace xmlns:noNamespaceSchemaLocation with NS0:noNamespaceSchemaLocation
c# xml replace xmlns:noNamespaceSchemaLocation with NS0:noNamespaceSchemaLocation

Time:04-03

I have a requirement to generate a xml file with a C# MVC application, with the following attributes:

<File NS0:noNamespaceSchemaLocation="myXML.xsd" xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance">

Notice that the noNamespaceSchemaLocation prefix is NS0

This is what I have right now:

<File xmlns:noNamespaceSchemaLocation="myXML.xsd" xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance">

In my file the prefix is xmlns, this is the first time I need to generate xml files, so I don't know if it is an error in the requirement of if I am just missing something, I am adding the the properties using the XmlSerealizerNamespaces class

var xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add( "NS0", "http://www.w3.org/2001/XMLSchema-instance" );
xmlNameSpace.Add( "noNamespaceSchemaLocation", "myXML.xsd" );

CodePudding user response:

I've given up using the Xml libraries to create the namespaces. Instead of just parse the string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApp1
{
    class Program
    {
        
        static void Main(string[] args)
        {
            string xml = "<File NS0:noNamespaceSchemaLocation=\"myXML.xsd\" xmlns:NS0=\"http://www.w3.org/2001/XMLSchema-instance\"></File>";

            XDocument doc = XDocument.Parse(xml);

        }
    }

}

CodePudding user response:

The xmlns:NS0 attribute is a namespace declaration, and you have correctly added this to XmlSerializerNamesapces.

The NS0:noNamespaceSchemaLocation is just an attribute, this needs to be part of your model. So a very simple model:

public class File
{
    [XmlAttribute("noNamespaceSchemaLocation", 
        Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string NoNamespaceSchemaLocation { get; set; } = "myXML.xsd"
}

Here you can see we define the attribute's name and namespace. The prefix for this namespace will be pulled from XmlSerializerNamespaces as NS0. The output will, when serialised, be:

<File xmlns:NS0="http://www.w3.org/2001/XMLSchema-instance" NS0:noNamespaceSchemaLocation="myXML.xsd" />

See this fiddle for a working demo.

  • Related