如何在.NET中解析union和list类型的值?

Abe*_*son 5 .net c# xml xsd

我有一个XML Schema,其中包含使用<xs:union>和的数据类型<xs:list>.这是一个摘录:

<xs:simpleType name="mixeduniontype">
  <xs:union memberTypes="xs:boolean xs:int xs:double xs:string"/>
</xs:simpleType>

<xs:simpleType name="valuelist">
  <xs:list itemType="xs:double"/>
</xs:simpleType>
Run Code Online (Sandbox Code Playgroud)

这是一个示例XML片段:

<value>42</value>
<value>hello</value>

<values>1 2 3.2 5.6</values>
Run Code Online (Sandbox Code Playgroud)

两个上部<value>元素是联合,下部<values>元素是列表.

我的问题是,我如何解析.NET中的元素<xs:union><xs:list>元素?

如何检查union元素中的值具有哪种数据类型?

如何提取列表元素中的元素并将其转换为C#列表?

System.XML中是否有内置的支持用于这种解析,或者我是否需要自己编写解析代码?

Jod*_*ell 0

希望得到更好的答案,但是,

我认为你需要自己写。

如果您想要一个适用于所有可能实例的通用解析器,xs:list并且xs:union您有一个更困难的问题,但对于您的特定模式,它相当简单。

//assuming parent is the containing node

//Parse your 'valuelist'
var newList = new List<double>();
foreach (string s in parent.XElement("values").value.Split(" ")) //should check for nulls here
{
    double value = 0.0;
    if (double.TryParse(s, value))
    {
        newList.Add(value);
    }
    else
    {
        \\throw some format exception
    }
}

//Parse your 'mixeduniontype'
Type valueType = typeof string;
double doubleValue;
int intValue;
boolean booleanValue;

var stringValue = parent.XElement("value").First();

if (double.TryParse(stringValue, doubleValue))
{
    valueType = typeof double;
}
else
{
    if (int.TryParse(stringValue, intValue))
    {
        valueType = typeof int;
    }
    else
    {
        if (bool.TryParse(stringValue, booleanValue))
             valueType = typeof boolean;
    }
}
Run Code Online (Sandbox Code Playgroud)