gpt4 book ai didi

c# - 使用 XML 序列化将属性放入不同的 XML 命名空间

转载 作者:数据小太阳 更新时间:2023-10-29 02:25:19 27 4
gpt4 key购买 nike

我正在使用 VSTS2008 + C# + .Net 3.0。我正在使用下面的代码来序列化 XML,这是我当前的代码和序列化的 XML 文件。我的目的是让 MyInnerObjectProperties 属于一个特殊的 XML 命名空间 ( http://foo/2009 ) 并将此命名空间设为默认命名空间。有什么想法可以实现吗?

当前输出:

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyObjectProperty>
<MyInnerObjectProperties>
<MyInnerObjectProperty>
<ObjectName>Foo Type</ObjectName>
</MyInnerObjectProperty>
<MyInnerObjectProperty>
<ObjectName>Goo Type</ObjectName>
</MyInnerObjectProperty>
</MyInnerObjectProperties>
</MyObjectProperty>
</MyClass>

当前代码:

public class MyClass
{
private MyObject[] _myObjectProperty;

[XmlElement(IsNullable=false)]
public MyObject[] MyObjectProperty
{
get
{
return _myObjectProperty;
}
set
{
_myObjectProperty = value;
}
}
}
public class MyObject
{
private MyInnerObject[] _myInnerObjectProperty;

[XmlArrayItemAttribute("MyInnerObjectProperty", typeof(MyInnerObject), IsNullable=false)]
public MyInnerObject[] MyInnerObjectProperties
{
get
{
return _myInnerObjectProperty;
}
set
{
_myInnerObjectProperty = value;
}
}
}

public class MyInnerObject
{
public string ObjectName;
}

public class Program
{
static void Main(string[] args)
{
XmlSerializer s = new XmlSerializer(typeof(MyClass));
FileStream fs = new FileStream("foo.xml", FileMode.Create);
MyClass instance = new MyClass();
instance.MyObjectProperty = new MyObject[1];
instance.MyObjectProperty[0] = new MyObject();
instance.MyObjectProperty[0].MyInnerObjectProperties = new MyInnerObject[2];
instance.MyObjectProperty[0].MyInnerObjectProperties[0] = new MyInnerObject();
instance.MyObjectProperty[0].MyInnerObjectProperties[0].ObjectName = "Foo Type";
instance.MyObjectProperty[0].MyInnerObjectProperties[1] = new MyInnerObject();
instance.MyObjectProperty[0].MyInnerObjectProperties[1].ObjectName = "Goo Type";

s.Serialize(fs, instance);

return;
}
}

最佳答案

这个怎么样:

[XmlArrayItemAttribute( Namespace = "http://foo.com/2009" /* other attr. params. */ )]
public MyInnerObject[] MyInnerObjectProperties
{
get { ... }
set { ... }
}

关于c# - 使用 XML 序列化将属性放入不同的 XML 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1228127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com