Remove namespace from generated XML in .NET [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
XmlSerializer: remove unnecessary xsi and xsd namespaces
I'm generating some XML using XMLSerializer and a class marked up with attributes. This XML is sent to a REST web service.
It generates the following XML:
<?xml version="1.0" encoding="utf-8"?>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<first-name>API</first-name>
<last-name>TestPersonDeleteMe</last-name>
<title>Delete me</title>
</person>
All would be well, except the web service I'm using doesn't understand the schema stuff and throws a 500 error.
Is there a way to stop XmlSerializer adding 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"' to the person tag?

if you use custom serializer try this
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
then add namespaces object to your serializer.

Related

Deserialize XML having Multiple xsi:type attributes

I am working on deserializing XML file where a same class has different namespaces. I am getting error while The specified type was not recognized. Here is a snippet from the XML I am trying to parse
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:SegmentHistory" Segment="ID13" eventDate="2014-04-03" eventTime="05:29:00" actionType="Change"/>
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:SsrHistory" eventDate="2014-04-03" eventTime="14:06:00" actionType="Add">
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:RemarkHistory" eventDate="2014-04-03" eventTime="15:02:00" actionType="Add">
Here is the sample XML
https://drive.google.com/file/d/1RDOAGa2TECSIauSHkdYTuSNuTWx5GVb8/view
Any suggestions would be highly appreciated.

Ignoring namespaces in XML deserialize

I want to deserialize XML into object. I have no controll what xml i'm reciving, and into what object I'm deserializing.
I tried this: Can I make XmlSerializer ignore the namespace on deserialization? and it worked... almost.
my xml
<request xmlns:a="http://schemas.datacontract.org/2004/07/My.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">
<a:ProfileInfo i:type="a:ProfileAndBSymbol">
<a:BSymbol>_47</a:BSymbol>
<a:ProfileSymbol>FAJNY</a:ProfileSymbol>
</a:ProfileInfo>
</request>
a:ProfileInfo works fine, but i:type thrown an exception. How to ignore i:?
exception is in Polish and it is like this:
InvalidOperationException: type is invalid. name= ProfileAndBSymbol,
namespace=http://schemas.datacontract.org/2004/07/My.Contracts

Error using "Xlmns" in XML document

I want to generate below code snippet into xml with c#:
<?xml version="1.0" encoding="utf-8" ?>
<PrincetonStorageRequest
xmlns="http://munichre.com/eai/dss/pct/v1.0"
requestId="RequestOut_MAG_Test_02"
timestampUtc="2015-02-19T09:25:30.7138903Z">
<StorageItems>
and my code is :
XmlWriter writer = XmlWriter.Create(fileName);
writer.WriteStartDocument(true);
writer.WriteStartElement("PrincetonStorageRequest");
writer.WriteAttributeString("xmlns","http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("requestId",name);
writer.WriteAttributeString("timestampUtc","2015-02-19T09:25:30.7138903Z");
writer.WriteStartElement("StorageItems");
But I am getting
"The prefix " cannot be redefined from " to within the same start element tag.
From your XML and the error, I believe it's because you are adding a default namespace after adding an element with no namespace declaration, so you're effectively creating an element and then changing its namespace.
Try the following code - it stops the error when I test it locally just for the XML I think you're trying to get:
XmlWriter writer = XmlWriter.Create(fileName);
writer.WriteStartDocument(true);
writer.WriteStartElement("PrincetonStorageRequest", "http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("xmlns", "http://example.com/abc/dss/pct/v1.0");
writer.WriteAttributeString("requestId", name);
writer.WriteAttributeString("timestampUtc", "2015-02-19T09:25:30.7138903Z");
writer.WriteStartElement("StorageItems");
So when I create the PrincetonStorageRequest element I am specifying a namespace URI.
Edit: Just to check, this is the XML that gets created but I did have to add the code to write the end elements:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<PrincetonStorageRequest xmlns="http://example.com/abc/dss/pct/v1.0" requestId="RequestOut_MAG_Test_02" timestampUtc="2015-02-19T09:25:30.7138903Z">
<StorageItems/>

Serializing XML in C#

I usually search the web high and low for my answers but this time I am drawing a blank. I'm using VS2005 to write code to POST xml to an API. I have classes setup in C# that I serialize into an XML document. The classes are below:
[Serializable]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Request
{
public RequestIdentify Identify;
public string Method;
public string Params;
}
[Serializable]
public class RequestIdentify
{
public string StoreId;
public string Password;
}
When I serialize this I get:
<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Identify>
<StoreId>00</StoreId>
<Password>removed for security</Password>
</Identify>
<Method>ProductExport</Method>
<Params />
</Request>
But the API returns a "No XML sent" error.
If I send the xml directly in a string as:
string xml = #"<Request><Identify><StoreId>00</StoreId><Password>Removed for security</Password></Identify><Method>ProductExport</Method><Params /></Request>";
effectively sending this xml (without the schema info in the "Request" tag):
<Request>
<Identify>
<StoreId>00</StoreId>
<Password>Removed for security</Password>
</Identify>
<Method>ProductExport</Method>
<Params />
</Request>
It seems to recognise the XML no problem.
So my question I guess is how can I change my current classes to Serialize into XML and get the XML as in the second case? I assume I need another "parent" class to wrap around the existing ones and use InnerXml property on this "parent" or something similar but I don't know how to do this.
Apologies for the question, I've only been using C# for 3 months and I'm a trainee developer who is having to teach himself on the job!
Oh and PS I don't know why but VS2005 really does not want to let me set these classes up with private variables and then use getters and setters on public equivalents so I have them written how they are for now.
Thanks in advance :-)
UPDATE:
As with most things it's very hard to find answers if you're not sure what you need to ask or how to word it but:
Once I knew what to look for I found the answers I needed:
Removing the XML declaration:
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
serializer.Serialize(xmlWriter, request);
}
string xmlText = stringWriter.ToString();
Removing/Setting the namespace (Thanks to above replies that helped find this one!):
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
Thanks for your help everyone who answered or pointed me in the right direction! And yes I did find articles to read once I knew what I was asking :-) It's the first time I have come unstuck in 3 months of teaching myself so I think I'm doing pretty well...
From Rydal's blog:
The XmlDocument object by default assigns a namespace to the XML string and also includes the declaration as the first line of the XML document. I definitely do not need or use those, therefore, I need to remove them. Here is how you go about doing just that.
Removing declaration and namespaces from XML serialization

How to do simple XML schema validation with no namespaces in C#

I have generated a set of classes using xsd.exe and created an XML document from the resulting generated code. I would now like to validate the serialized class instance against the original xsd.
My XML is like this:
<?xml version="1.0" encoding="UTF-8"?>
<MyRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-- rest of XML document here
</MyRoot>
My XSD is like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyRoot" type="MyRootType"/>
-- MyRootType definition and rest of XSD
</xs:schema>
When I try to validate the XML using a XmlReader, I get the following error:
"The 'MyRoot' element is not declared."
What could be wrong?
In your MyRoot element, you need to add the location of the XSD. I would also recommend defining the namespace (unless you have good reason not to).
<api:MyRoot xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:api='http://www.myserver.com/schema'
xsi:schemaLocation='http://www.myserver.com/schema http://www.myserver.com/schema/websuiterecord.xsd'>
</api:MyRoot>
This way, the validation tool knows where to find your XSD to validate your XML against.
The approach was correct, but the XSD was not infact being read. I corrected this and it worked as expected.

Categories

Resources