如何在xs工具生成的代码中使用带有xs:any / ## any的复杂类型并混合使用

时间:2011-02-11 13:14:20

标签: c# xml-serialization xsd xmlnode

我的XML架构中有以下复杂类型:

<xs:complexType name="Widget" mixed="true">
    <xs:sequence>
        <xs:any namespace="##any" processContents="skip" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

派生XML中的元素可以包含字符串或者可以包含格式良好的XML,因此mixed属性为true。

当我通过.NET XSD工具运行时,我得到以下生成代码:

public partial class Widget{

    private System.Xml.XmlNode[] anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    [System.Xml.Serialization.XmlAnyElementAttribute()]
    public System.Xml.XmlNode[] Any {
        get {
            return this.anyField;
        }
        set {
            this.anyField = value;
        }
    }
}

我的问题是我不完全确定如何使用它。最终我需要能够将widget的值设置为:

<widget>Hello World!</widget>

<widget>
  <foo>Hello World</foo>
</widget>

两者都验证了架构

2 个答案:

答案 0 :(得分:2)

为此:

<widget>  
    <foo>Hello World</foo>
</widget>

使用此:

XmlDocument dom = new XmlDocument();
Widget xmlWidget = new Widget();
xmlWidget.Any = new XmlNode[1];
xmlWidget.Any[0] = dom.CreateNode(XmlNodeType.Element, "foo", dom.NamespaceURI);
xmlWidget.Any[0].InnerText = "Hello World!";

为此:

<widget>Hello World!</widget>

使用此:

XmlDocument dom = new XmlDocument();
XmlNode node = dom.CreateNode(XmlNodeType.Element, "foo", dom.NamespaceURI);
node.InnerText = "Hello World";

Widget w = new Widget();
w.Any = new XmlNode[1];
w.Any[0] = node.FirstChild; 

答案 1 :(得分:0)

将此作为答案发布,因为它在技术上有效并回答了问题。然而,这似乎是一个非常讨厌的黑客。因此,如果有人有另一种更好的解决方案,那我就是全心全意。

string mystring= "if I check this code in it will at least have comedy value";

XmlDocument thisLooksBad = new XmlDocument();
thisLooksBad.LoadXml("<temp>" + mystring + "</temp>");

Widget stringWidget = new Widget();
stringWidget.Any = new XmlNode[1];
stringWidget.Any[0] = thisLooksBad.SelectSingleNode("/temp").FirstChild;

正如您所看到的,我将我的字符串放入包含在标签中的XmlDocument中,这可以正常工作,编译和序列化 - 所以是的,这是一个解决方案,但这让我觉得这是一个讨厌的黑客。

string myxml = "<x><y>something</y></x>";

XmlDocument thisDoesntLookSoBad = new XmlDocument();
thisLooksBad.LoadXml(myxml);

Widget xmlWidget = new Widget();
xmlWidget.Any = new XmlNode[1];
xmlWidget.Any[0] = thisDoesntLookSoBad;

在这个例子中,我将XML放入XmlDocument,然后将其分配给生成的类。这更有意义,因为我使用XML而不是原始字符串。

奇怪的是,我也可以做到这一点并且也可以(但也是一个讨厌的黑客):

string myxml = "<x><y>something</y></x>";

XmlDocument dom = new XmlDocument();
dom.LoadXml("<temp>" + myxml + "</temp>");

Widget xmlWidget = new Widget();
xmlWidget.Any = new XmlNode[1];
xmlWidget.Any[0] = dom.SelectSingleNode("/temp").FirstChild;