Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将schemaLocation添加到XML序列化列表<;T>;使用XmlSerializer_C#_Xml - Fatal编程技术网

C# 将schemaLocation添加到XML序列化列表<;T>;使用XmlSerializer

C# 将schemaLocation添加到XML序列化列表<;T>;使用XmlSerializer,c#,xml,C#,Xml,在序列化List时,我试图向XML根元素添加schemaLocation属性。如果我只序列化一个对象,但不处理列表,那么代码就可以正常工作。我当前的代码: public class SomeObject { public int Id { get; set; } public string Name { get; set; } } public class XmlListContainer<T> : List<T> { [XmlAttribute(

在序列化
List
时,我试图向XML根元素添加
schemaLocation
属性。如果我只序列化一个对象,但不处理列表,那么代码就可以正常工作。我当前的代码:

public class SomeObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class XmlListContainer<T> : List<T>
{
    [XmlAttribute(Namespace = XmlSchema.InstanceNamespace)]
    public string schemaLocation = "http :// localhost/someschema";
}
public class BuildXml
{
    public static void GetXml()
    {
        var list = new XmlListContainer<SomeObject>()
        {
            new SomeObject() { Id = 1, Name = "One" },
            new SomeObject() { Id = 2, Name = "Two" },
        };
        var objectToXml = list;
        string output;
        using (var writer = new StringWriter())
        {
            var xs = new XmlSerializer(objectToXml.GetType());
            var nameSpaces = new XmlSerializerNamespaces();
            nameSpaces.Add("xsi", "http :// www.w3.org/2001/XMLSchema-instance");
            xs.Serialize(writer, objectToXml, nameSpaces);
            output = writer.GetStringBuilder().ToString();
            writer.Close();
        }
        Console.WriteLine(output);
    }
}
如果我将代码更改为

public class SomeObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    [XmlAttribute(Namespace = XmlSchema.InstanceNamespace)]
    public string schemaLocation = "http :// localhost/someschema";
}
...
var objectToXml = new SomeObject() { Id = 1, Name = "One" };
…一切看起来都很好,但我需要清单

<SingleObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost/someschema">


序列化
List
时是否可以添加
schemaLocation
属性?

预期的输出是什么?XML文件只能有一个根标记。您的列表正在创建多个根标记。在添加列表之前添加一个根标记。jdweng,在当前版本中只有一个根标记,名为ArrayOfSomeObject。
<SingleObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost/someschema">