C#XmlSerializer - XML文档中存在错误0,0)<nodename>不期望</nodename>

时间:2012-03-26 21:13:37

标签: c# xml

我之前发布了这个问题的不同风格,没有任何喜悦。我希望重构的问题会有所帮助。

基本上,我将XML字符串加载到XDocument中,然后使用XDocument.GetReader()返回XmlReader。从这里开始,我使用XmlSerializer来反序列化以下XML:

<?xml version='1.0' encoding='UTF-8'?>
<osgb:FeatureCollection
xmlns:osgb='http://www.ordnancesurvey.co.uk/xml/namespaces/osgb'
xmlns:gml='http://www.opengis.net/gml'
xmlns:xlink='http://www.w3.org/1999/xlink'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://www.ordnancesurvey.co.uk/xml/namespaces/osgb http://www.ordnancesurvey.co.uk/xml/schema/v7/OSDNFFeatures.xsd'
fid='GDS-58116-1'>
  <gml:description>OS</gml:description>
  <gml:boundedBy>
    <gml:null>unknown</gml:null>
  </gml:boundedBy>
  <osgb:queryTime>2009-07-30T02:35:17</osgb:queryTime>
  <osgb:queryExtent>
    <osgb:Rectangle srsName='osgb:BNG'>
      <gml:coordinates>291000.000,92000.000 293000.000,94000.000</gml:coordinates>
    </osgb:Rectangle>
  </osgb:queryExtent>  
</osgb:FeatureCollection>

到这个类(使用XSD生成)

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.ordnancesurvey.co.uk/xml/namespaces/osgb")]
[System.Xml.Serialization.XmlRootAttribute("FeatureCollection", Namespace = "http://www.ordnancesurvey.co.uk/xml/namespaces/osgb", IsNullable = false)]
public partial class FeatureCollectionType : AbstractFeatureCollectionType
{

    private System.DateTime queryTimeField;

    private GeometryPropertyType queryExtentField;

    private System.DateTime queryChangeSinceDateField;

    private bool queryChangeSinceDateFieldSpecified;

    private FeatureAssociationType[] _featureMemberField;

    private BoundingShapeType boundedBy1Field;

    //  more properties

}

内部异常显示:<FeatureCollection xmlns='http://www.ordnancesurvey.co.uk/xml/namespaces/osgb'> was not expected

我无法看到问题所在。我不需要在集合上面有根节点吗?

1 个答案:

答案 0 :(得分:2)

我测试了一个简化版本(从FeatureCollectionType中移除了所有属性),它没有抛出第一个元素:

private static string xml = 
@"<?xml version='1.0' encoding='UTF-8'?>
<osgb:FeatureCollection
   xmlns:osgb='http://www.ordnancesurvey.co.uk/xml/namespaces/osgb'
   xmlns:gml='http://www.opengis.net/gml'
   xmlns:xlink='http://www.w3.org/1999/xlink'
   xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
   xsi:schemaLocation='http://www.ordnancesurvey.co.uk/xml/namespaces/osgb http://www.ordnancesurvey.co.uk/xml/schema/v7/OSDNFFeatures.xsd'
   fid='GDS-58116-1'>
</osgb:FeatureCollection>";

public static void RunSnippet()
{
    using (var sr = new StringReader(xml))
    {
        var xs = new XmlSerializer(typeof(FeatureCollectionType));
        var obj = xs.Deserialize(sr);
        Console.WriteLine("if you are reading this, it didn't throw");
    }
}

您如何实例化XmlSerializer