简体   繁体   English

c# xml 将 xmlns:noNamespaceSchemaLocation 替换为 NS0:noNamespaceSchemaLocation

[英]c# xml replace xmlns:noNamespaceSchemaLocation with NS0:noNamespaceSchemaLocation

I have a requirement to generate a xml file with a C# MVC application, with the following attributes:我需要使用 C# MVC 应用程序生成一个 xml 文件,该文件具有以下属性:

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

Notice that the noNamespaceSchemaLocation prefix is NS0注意 noNamespaceSchemaLocation 前缀是 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在我的文件中,前缀是 xmlns,这是我第一次需要生成 xml 个文件,所以我不知道这是否是一个错误,如果我只是遗漏了一些东西,我正在使用添加属性XmlSerealizerNamespaces class

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

The xmlns:NS0 attribute is a namespace declaration, and you have correctly added this to XmlSerializerNamesapces . xmlns:NS0属性是命名空间声明,您已将其正确添加到XmlSerializerNamesapces中。

The NS0:noNamespaceSchemaLocation is just an attribute, this needs to be part of your model. So a very simple model: NS0:noNamespaceSchemaLocation只是一个属性,它需要成为您的 model 的一部分。所以一个非常简单的 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 .此命名空间的前缀将从XmlSerializerNamespaces中作为NS0提取。 The output will, when serialised, be:序列化后,output 将是:

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

See this fiddle for a working demo.有关工作演示,请参阅此小提琴

I've given up using the Xml libraries to create the namespaces.我已经放弃使用 Xml 库来创建命名空间。 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);

        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM