7

我的 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,因此混合属性为真。

当我通过 .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>Hello World!</widget>

或者

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

两者都验证了架构

4

2 回答 2

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; 
于 2011-02-11T21:22:25.643 回答
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 中,这可以正常工作、编译和序列化 - 所以是的,它是一个解决方案,但它让我觉得这是一个讨厌的 hack。

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;
于 2011-02-11T21:10:09.587 回答