1

I am trying to serialize a xml file that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<MainNode xmlns="http://test">
  <SubNode xmlns:xsi="http://test2" xmlns="test3">
    <setting name = "1" value = "2"/>
  </SubNode>
</MainNode>

I created a class this like:

[XmlRootAttribute(Namespace = "test")]    
public class MainNode
{
    [XmlElement("SubNode")]
    public SubNode SubNode { get; set; }     
}

public class SubNode
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("value")]
    public string Value { get; set; }
}

Deserialization fails because I have xmlns:xsi and xlms in my Sub Node. How should i include the namespace in my sub node?

1 Answer 1

2

There is quite a bit wrong with your approach. Hopefully this fully solves your issue, but nonetheless this will help at least get your structure correct.

You have a SubNode class with Name and Value. If you look at your XML, your <SubNode> does not contain these attributes/elements. It is your <setting> node that does. To fix this you need to create a SubNode and setting class.

[XmlRoot(Namespace="http://test")]
public class MainNode
{
    [XmlElement(Namespace="test3")]
    public SubNode SubNode { get; set; }
}

public class SubNode
{
    [XmlElement("setting")]
    public SettingsNode Settings { get; set; }
}

public class SettingsNode
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlAttribute("value")]
    public string Value { get; set; }
}

Notice the Namespace set on the XmlElementAttribute on property SubNode. This should force all children (unless specifically overriden) that it is of that namespace.

I don't necessarily think you need to worry about the xsi attribute, but if you do, I believe you will need to look at the XmlNamespaceDeclarationsAttribute. This should at least get you the correct structure.

EDIT: Just tested and made a small correction. This appears to deserialize your example XML just fine. Here is my small test:

void Main()
{
    string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<MainNode xmlns=""http://test"">
  <SubNode xmlns:xsi=""http://test2"" xmlns=""test3"">
    <setting name = ""1"" value = ""2""/>
  </SubNode>
</MainNode>";

    var serializer = new XmlSerializer(typeof(MainNode));
    using (TextReader reader = new StringReader(xml))
    {
        var result = (MainNode)serializer.Deserialize(reader);
        Console.WriteLine(result.SubNode.Settings.Value);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.