How to remove the xmlns:xsd attribute but keep xml

2019-07-21 17:23发布

问题:

I am using the .Net XmlSerializer to serialize an object to an XML document, in a C# Windows Forms application.

The root element should end up looking like:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:noNamespaceSchemaLocation="file:///C:/data//MySchema.xsd">
  <!-- ... -->
</root>  

In a partial class (to join the partial class created by xsd.exe), I have added the following property to add the xsi:noNamespaceSchemaLocation attribute.

[XmlAttribute("noNamespaceSchemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string xsiNoNamespaceSchemaLocation = @"file:///C://data//MySchema.xsd";

And to remove all the other namespaces, but keep the xsi one I have used:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

And then passed ns to the XmlSerializer.Serialize() method.

This works so far, but I'm not sure if this is correct. It feels like I'm removing what is there by default, only to try add a piece of it back again... seems like a code smell.

Maybe is there a better way that only removes the xsd but leaving the default xsi, so I don't need to add it back in again?

Note: There is an unanswered question on this already from some time back here, the only suggested answer does not suit as it removes both xsd and xsi attributes.

回答1:

What you've done looks correct to me.

You can look at the internals and see that XmlSerializer uses DefaultNamespaces when none are specified.

This is the same as if you were to supply and XmlSerializerNamespaces containing prefixes / namespaces for xsi and xsd and is why you see declarations for xsi and xsd by default.

The correct thing to do to 'remove' xsd would be to supply an XmlSerializerNamespaces instance that doesn't contain that prefix / namespace.



回答2:

I also encountered a problem like you. I used linq first but it did not work. Later I found a better tool XSLT. You can use XSLT like Online.