Peter Peter - 10 days ago 6
C# Question

Unexpected term in XML

I want to deserialize an XML an get an exception

<ehd xmlns='urn:ehd/001> was not expected
. I have tried different namespaces but nothing helped and so I have no idea what I can do to resolve it.

The first lines of the XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<ehd:ehd ehd_version="1.40" xmlns:ehd="urn:ehd/001" xmlns="urn:ehd/kts/001">
<ehd:header>
<ehd:id EX="11944b3a-4f86-4da2-af6e-e24bedd6b523" RT="74"/>
<ehd:document_type_cd V="KTS"/>
</ehd:header>
<ehd:body>
<kostentraeger_liste>
<kostentraeger V="01101">
<gueltigkeit V="1994-01-01.."/>


And here my code for deserialisation:

var stream = new FileStream(@"I:\medatis\kleinprojekte\KassenlisteKBV\KbvRohdaten\KTStamm_2017_1.xml", FileMode.Open, FileAccess.Read);
var seri = new XmlSerializer(typeof(KostentraegerListe));
KostentraegerListe liste = null;

try
{
liste = (KostentraegerListe) seri.Deserialize(stream);
stream.Close();
}
catch (Exception e)
{
Trace.WriteLine(e.GetBaseException());
}


And here the serializable classes:

[Serializable]
[DebuggerStepThrough]
[XmlType(AnonymousType = true)]
[XmlRoot(ElementName="kostentraeger_liste", Namespace = "urn:ehd/001", IsNullable = false)]
public class KostentraegerListe
{
private List<Kostentraeger> _kostentraegerListe;

[XmlElement("kostentraeger")]
public List<Kostentraeger> Kostentraeger
{
get { return _kostentraegerListe ?? (_kostentraegerListe = new List<Kostentraeger>()); }
set { _kostentraegerListe = value; }
}
}

[SerializableAttribute]
[DebuggerStepThrough]
[XmlType(AnonymousType = true)]
public class Kostentraeger
{
private string _kostentraegernummer = String.Empty;

[XmlAttribute("V")]
public string Kostentraegernummer
{
get { return _kostentraegernummer; }
set { _kostentraegernummer = value; }
}
}

Answer

The main issue is that the classes you've defined only represent a fragment of the document you are deserialising. You need to define classes to represent at least the ehd and body elements, and the body element will contain kostentraeger_liste. The bare minimum required is below:

[XmlRoot("ehd", Namespace = "urn:ehd/001")]
public class Ehd
{
    [XmlElement("body")]
    public Body Body { get; set; }
}

public class Body
{
    [XmlElement("kostentraeger_liste", Namespace = "urn:ehd/kts/001")]
    public KostentraegerListe KostentraegerListe { get; set; }
}

public class KostentraegerListe
{
    [XmlElement("kostentraeger")]
    public List<Kostentraeger> Kostentraeger { get; set; }
}

public class Kostentraeger
{
    [XmlAttribute("V")]
    public string Kostentraegernummer { get; set; }
}

See this fiddle for a working demo.