0

I'm serializing XML from a C# class, and I need to include a namespace in the root and child elements.

When I add a namespace from XmlSerializerNamespaces, it adds all of the namespaces to the root element.

I need to add some namespaces to the root as well as some to the Grouping1 Element.

Thanks

<root>
  <Element>
    <Grouping1>
      <Item1>First1</Item1>
      <Item2>Second1</Item2>
    </Grouping1>
    <Grouping2>
      <Item3>Third1</Item3>
    </Grouping2>
  </Element>
  <Element>
    <Grouping1>
      <Item1>First2</Item1>
      <Item2>Second2</Item2>
    </Grouping1>
    <Grouping2>
      <Item3>Third2</Item3>
    </Grouping2>
  </Element>
</root>
2

1 Answer 1

1

Namespaces can be added to any XML element using XmlNamespaceDeclarations in a child class.

 [XmlNamespaceDeclarations]
 public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(new[]{new XmlQualifiedName("sig", "urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2")});

Sample Code

[Serializable]
[XmlRoot(ElementName = "root")]
public class RootClass
{
    [XmlElement(ElementName = "body", Namespace = "httpenv")]
    public BodyClass body = new BodyClass();
}

[Serializable]
public class BodyClass
{
    [XmlElement(ElementName = "element", Namespace = "httpsos")]
    public SOSClass element = new SOSClass();
}

[Serializable]
public class SOSClass
{
    // This will be used by XML serializer to determine the namespaces
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces( new[] { new XmlQualifiedName("sos", "httpsos"), });
}
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.