I just generated a class using the xsd.exe (See previous question) and then I tried to use it to deserialize my XML file.
My XML files start like this:
<?xml version="1.0" encoding="utf-8"?>开发者_开发技巧;
<?xml-stylesheet type='text/xsl' href='STIG_unclass.xsl'?>
<Benchmark xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cpe="http://cpe.mitre.org/language/2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" id="Windows_2003" xml:lang="en" xsi:schemaLocation="http://checklists.nist.gov/xccdf/1.1 http://nvd.nist.gov/schema/xccdf-1.1.4.xsd http://cpe.mitre.org/dictionary/2.0 http://cpe.mitre.org/files/cpe-dictionary_2.1.xsd" xmlns="http://checklists.nist.gov/xccdf/1.1">
and the generated class from xsd.exe starts off like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://checklists.nist.gov/xccdf/1.1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://checklists.nist.gov/xccdf/1.1", IsNullable = false)]
public partial class Benchmark
but when I try and deserialize my XML file, using the following code:
var groups = new List<Benchmark>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Benchmark>));
using (TextReader textReader = new StreamReader(open.FileName))
groups = (List<Benchmark>)serializer.Deserialize(textReader); // ERROR HERE
SetGroups(groups);
I get an error message that says "There is an error in XML document (3, 2)." with an inner exception that says: "http://checklists.nist.gov/xccdf/1.1'> was not expected."
What am I doing wrong?
Dang, I figured it out...
I was serializing the object as List<Benchmark>
instead of Benchmark
.... Changed that and everything was fixed!
I recognize this is a long-closed thread, but I also ran into this problem when using xsd.exe for the first time and had a different solution. It turns out that you MUST include the namespace in an xmlns, or you will receive an error of
<config xmlns=''> was not expected.
My XML file looked like this
<?xml version="1.0" encoding="utf-8" ?>
<MyClass>
...
After changing it to
<?xml version="1.0" encoding="utf-8" ?>
<MyClass xmlns="http://tempuri.org/MyClass.xsd>
Everything deserialized beautifully.
精彩评论