micdev42
micdev42

Reputation: 87

How to use XmlSerializer to deserialise XML that has multiple xlmns attributes

I'm trying to deserialize an XML file like this (it's actually a maven POM but that's not important right now...):

<?xml version="1.0" encoding="UTF-8"?>
<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion> 
</project>

I have a POM class that I have defined by hand:

[XmlRoot(Namespace= "http://maven.apache.org/POM/4.0.0")]
public class POM
{
    [XmlElement("modelVersion")]
    public string ModelVersion{ get; set; }
}

... and my deserialize code:

FileStream fileStream = File.Open("pom.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
var codec = new XmlSerializer(typeof(POM));
var pom = (POM) codec.Deserialize(fileStream);

When I run this I get InvalidOperationException: 'project xmlns="http://maven.apache.org/POM/4.0.0"' was not expected.

How to I get the deserialzer to cope with the additional xmlns attribute and the xsi:schemalocation ?

When I remove them the code runs without error.

Thanks, Michael

Upvotes: 2

Views: 415

Answers (2)

taher chhabrawala
taher chhabrawala

Reputation: 4120

put ElementName="project" in the xml root attribute see below

[XmlRoot(ElementName="project" ,Namespace = "http://maven.apache.org/POM/4.0.0")]
 public class POM
 {
    [XmlElement("modelVersion")]
    public string ModelVersion { get; set; }
 }

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Simply add ElementName to XmlRootAttribute, because your root element has project name, i.e.:

[XmlRoot(Namespace = "http://maven.apache.org/POM/4.0.0", ElementName = "project")]

Upvotes: 1

Related Questions