I have an XML file which starts something like this:-
<?xml version="1.0" encoding="UTF-8"?>
<Deal xmlns="http://schemas.datacontract.org/2004/07/DealioCapLinkLib.Dealio.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AccountingDate>2019-09-30</AccountingDate>
When I try to convert this object to XML like below, I get an error:-
private static void Prod_Error_Test()
{
string prodRequestXml = File.ReadAllText("ProdXml.xml");
var serializer = new XmlSerializer(typeof(Service.Deal));
Service.Deal request ;
var reader = new StringReader(prodRequestXml);
request = (Service.Deal)serializer.Deserialize(reader);
}
The Error Message is "There is an error in XML document (2, 2).". The Inner Exception Message is "<Deal xmlns='http://schemas.datacontract.org/2004/07/DealioCapLinkLib.Dealio.Models'> was not expected."
Service.Deal is a WCF Proxy.So I may not be able to add any attributes. Can anyone suggest what to do here ?
Being a WCF proxy doesn't preclude adding attributes; in particular, it is usually a partial class, which means you can have your own separate file, with:
namespace Service
{
[XmlRoot("Deal", Namespace = "http://schemas.datacontract.org/2004/07/DealioCapLinkLib.Dealio.Models")]
partial class Deal {}
}
But ultimately: if the type doesn't conveniently fit the XML: stop fighting it - create a new separate type that fits the XML and works well with XmlSerializer, and then map between the two types in your own code.
Related
I am writing a routine in C# to validate an Xml file using XmlDocument. Everything seems to be fine except something that i cant understand.
my xml:
<?xml version="1.0" encoding="utf-8"?>
<bdo_fosfec:RegistrosPagosElement xsi:type="bdo_fosfec:RegistrosPagos"
xmlns:bdo_fosfec="http://asocajas.hp.com/bdo_fosfec"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<registro54 xsi:type="bdo_fosfec:Registro54">
<registro82 xsi:type="bdo_fosfec:Registro82">
...
</registro82>
</registro54>
<registro54 xsi:type="bdo_fosfec:Registro54">
<registro82 xsi:type="bdo_fosfec:Registro82">
...
</registro82>
</registro54>
</bdo_fosfec:RegistrosPagosElement>
and the xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://asocajas.hp.com/bdo_fosfec" xmlns:tns1="http://asocajas.hp.com/bdo_fosfec" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://asocajas.hp.com/bdo_fosfec">
<xsd:annotation>
<xsd:documentation>BOMORIGIN::platform:/resource/bdo_Fosfec/Business%20Objects/bdo_Fosfec.bom#_rs4Sa9itEeSR9aIqvSWzoQ</xsd:documentation>
</xsd:annotation>
...
</xsd:schema>
here is my code to validate my xml against xsd,
XmlDocument xml = new XmlDocument();
xml.Schemas.Add("http://asocajas.hp.com/bdo_fosfec", PathFileXSD);
//load my xml
xml.LoadXml(stringXml);
//event handler to manage the errors from XmlDocument object
ValidationEventHandler veh = new ValidationEventHandler(ErrorValidacion);
//validate my xml
xml.Validate(veh);
and the event handler ErrorValidacion will show me the error
private void ErrorValidacion(object sender, ValidationEventArgs e)
{
string concat = string.Empty;
switch (e.Severity)
{
case XmlSeverityType.Error:
concat = string.Format("Error: {0}", e.Message);
break;
case XmlSeverityType.Warning:
concat = string.Format("Warning {0}", e.Message);
break;
}
}
When run my program the error msj is:
This is an invalid xsi:type 'http://asocajas.hp.com/bdo_fosfec:RegistrosPagos'.
The thing is.. why this message?, The xsi:type for my xml isn't
http://asocajas.hp.com/bdo_fosfec:RegistrosPagos
The xsi:type for my xml is
xsi:type="bdo_fosfec:RegistrosPagos"
Where does the xsi:type http://asocajas.hp.com/bdo_fosfec:RegistrosPagos come from?
So, How can I solve this issue without having to modify the xml? (Because the xml is based on an xslt)
The error message is saying that the XSD does not include a declaration for RegistrosPagos in the http://asocajas.hp.com/bdo_fosfec namespace.
It is using the expanded form of the namespace to report the error instead of the namespace prefix because the namespace prefix is arbitrary and insignificant by definition. This is entirely proper.
In fact, the XSD you've posted does not include a RegistrosPagos in the http://asocajas.hp.com/bdo_fosfec namespace.
See also: How to restrict the value of an XML element using xsi:type in XSD?
I've been using xsd2code v3.4.
So far I'm pretty close to getting it to work, however I'm facing one glaring issue and I can't seem to find any solutions. When my XML gets generated after I serialize my object, it's adding an additional complex type that is named exactly like the class. This is what I currently get. Notice how it's adding an unnecessary collection right after an order line:
<?xml version="1.0" encoding="utf-8"?>
<CORE_PO_INBOUND_V2 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<INTEGRATION_MESSAGE_CONTROL>
<ACTION>FULL_UPDATE</ACTION>
<COMPANY_CODE>COMPANY</COMPANY_CODE>
<ORG_CODE>COMPANY</ORG_CODE>
<MESSAGE_TYPE>INBOUND_ENTITY_INTEGRATION</MESSAGE_TYPE>
<USERID>COMPANY</USERID>
<RECEIVER>TA15</RECEIVER>
<SENDER>COMPANY</SENDER>
<BATCH_ID>1234</BATCH_ID>
<BUS_KEY>
<ORG_CODE>COMPANY</ORG_CODE>
<PO_NUMBER>1234</PO_NUMBER>
</BUS_KEY>
</INTEGRATION_MESSAGE_CONTROL>
<PURCHASE_ORDER_HEADER>
<CTRY_OF_EXPORT>TR</CTRY_OF_EXPORT>
<CTRY_OF_IMPORT>US</CTRY_OF_IMPORT>
<CURRENCY_CODE>USD</CURRENCY_CODE>
<INCOTERM_CODE>011</INCOTERM_CODE>
<ORG_CODE>COMPANY</ORG_CODE>
<SOURCE_TX_ID>THING</SOURCE_TX_ID>
<PO_NUMBER>1234</PO_NUMBER>
<PURCHASE_ORDER_LINE>
<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE>
<BUSINESS_UNIT>BCA</BUSINESS_UNIT>
<COMMERCIAL_UOM>EA</COMMERCIAL_UOM>
<CTRY_OF_IMPORT>US</CTRY_OF_IMPORT>
<CURRENCY_CODE>USD</CURRENCY_CODE>
<DEPARTMENT>602</DEPARTMENT>
<LINE_ID>1</LINE_ID>
</CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE>
</PURCHASE_ORDER_LINE>
<PURCHASE_ORDER_HEADER_PARTNER>
<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_HEADER_PARTNER>
<REF_RESOLUTION_PARTNER>Stuff</REF_RESOLUTION_PARTNER>
</CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_HEADER_PARTNER>
</PURCHASE_ORDER_HEADER_PARTNER>
</PURCHASE_ORDER_HEADER>
</CORE_PO_INBOUND_V2>
This is what I actually want:
<?xml version="1.0" encoding="utf-8"?>
<CORE_PO_INBOUND_V2 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<INTEGRATION_MESSAGE_CONTROL>
<ACTION>FULL_UPDATE</ACTION>
<COMPANY_CODE>COMPANY</COMPANY_CODE>
<ORG_CODE>COMPANY</ORG_CODE>
<MESSAGE_TYPE>INBOUND_ENTITY_INTEGRATION</MESSAGE_TYPE>
<USERID>COMPANY</USERID>
<RECEIVER>TA15</RECEIVER>
<SENDER>COMPANY</SENDER>
<BATCH_ID>1234</BATCH_ID>
<BUS_KEY>
<ORG_CODE>COMPANY</ORG_CODE>
<PO_NUMBER>1234</PO_NUMBER>
</BUS_KEY>
</INTEGRATION_MESSAGE_CONTROL>
<PURCHASE_ORDER_HEADER>
<CTRY_OF_EXPORT>TR</CTRY_OF_EXPORT>
<CTRY_OF_IMPORT>US</CTRY_OF_IMPORT>
<CURRENCY_CODE>USD</CURRENCY_CODE>
<INCOTERM_CODE>011</INCOTERM_CODE>
<ORG_CODE>COMPANY</ORG_CODE>
<SOURCE_TX_ID>THING</SOURCE_TX_ID>
<PO_NUMBER>1234</PO_NUMBER>
<PURCHASE_ORDER_LINE>
<BUSINESS_UNIT>BCA</BUSINESS_UNIT>
<COMMERCIAL_UOM>EA</COMMERCIAL_UOM>
<CTRY_OF_IMPORT>US</CTRY_OF_IMPORT>
<CURRENCY_CODE>USD</CURRENCY_CODE>
<DEPARTMENT>602</DEPARTMENT>
<LINE_ID>1</LINE_ID>
</PURCHASE_ORDER_LINE>
<PURCHASE_ORDER_HEADER_PARTNER>
<REF_RESOLUTION_PARTNER>Stuff</REF_RESOLUTION_PARTNER>
</PURCHASE_ORDER_HEADER_PARTNER>
</PURCHASE_ORDER_HEADER>
</CORE_PO_INBOUND_V2>
Is there some setting I'm using incorrectly? I have it set to work with List collections. Seems as if this problem only exists for collections of a class that's generated from this tool.
Edit: Adding some snippets of the designer class that gets generated by xsd2code. Note that this file is pretty large (almost 10k lines...), so I'm not going to post the whole thing here, but rather the chunks that pertain to the purchase order line collections of elements:
public partial class CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADER : EntityBase<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADER>
{
private List<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE> pURCHASE_ORDER_LINEField;
public List<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE> PURCHASE_ORDER_LINE
{
get
{
if ((this.pURCHASE_ORDER_LINEField == null))
{
this.pURCHASE_ORDER_LINEField = new List<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE>();
}
return this.pURCHASE_ORDER_LINEField;
}
set
{
this.pURCHASE_ORDER_LINEField = value;
}
}
}
public partial class CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE : EntityBase<CORE_PO_INBOUND_V2PURCHASE_ORDER_HEADERPURCHASE_ORDER_LINE>
{
private System.Nullable<decimal> aREAField;
private bool aREAFieldSpecified;
private string aREA_UOMField;
...
}
I think I found a solution. I spoke with a colleague whom had done something similar. He said he used the native "xsd" and not "xsd2code". We did a compare on what got generated and noticed that on the arrays (in my case, I use lists...), he had the following annotation:
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
Is there a way to trigger this same annotation via xsd2code? Looks like without it extra elements get generated upon executing the serializer.
I need to read some XML files that follow the ONIX standard
See: http://www.editeur.org/93/Release-3.0-Downloads/
To do this i downloaded the ONIX 3.0 XSD:
http://www.editeur.org/files/ONIX%203/ONIX_BookProduct_XSD_schema+codes_Issue_25.zip
Using the downloaded XSD and this command "xsd your.xsd /classes" i created classes that i want to use.
When trying to create a new Xml Serializer like so:
var xmls = new XmlSerializer(typeof(Model.ONIX.editeur.ONIXMessage));
I get and exception
"There was an error reflecting type 'Model.ONIX.editeur.ONIXMessage'."
When i drill down through the inner exceptions i end up with this message:
"{"Member 'Text' cannot be encoded using the XmlText attribute. You
may use the XmlText attribute to encode primitives, enumerations,
arrays of strings, or arrays of XmlNode."}"
I am not sure what to do, is something wrong with the XSD? Any suggestions?!
Edit
public static List<Model.ONIX.editeur.Product> GetProductsDataFromOnixFile(string onixFileLocation)
{
var xmls = new XmlSerializer(typeof(Model.ONIX.editeur.ONIXMessageRefname));
using (var reader = XmlReader.Create(onixFileLocation))
{
if (xmls.CanDeserialize(reader))
{
var onixMessage = (Model.ONIX.editeur.ONIXMessage)xmls.Deserialize(reader);
return onixMessage.Items.OfType<Model.ONIX.editeur.Product>().ToList();
}
throw new Exception(string.Format("Cant read the file {0} as Onix", onixFileLocation));
}
}
I know this question is old but I assume others with specific Onix issues will run into this.
Here is how I got it to work.
In the reference xsd are two includes in the top. Here I copy/pasted the other two files in.
<xs:include schemaLocation="ONIX_BookProduct_CodeLists.xsd" />
<xs:include schemaLocation="ONIX_XHTML_Subset.xsd" />
I.e. these lines are replaced in the file with the corresponding file.
Then I did the
xsd ONIX_BookProduct_3.0_reference.xsd /classes
And then it generates the .cs file. And the only issue I had here was I had to remove a text attribute from all fields that was e.g. List147, but not from the fields that was string. E.g. I had to remove the attribute from generated code like this:
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public List121 textscript {
get {
return this.textscriptField;
but not from attributes like this
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
I'm trying to validate an XBRL document, but I'm a bit lost. The XBRL is a (simplified) example of the Dutch taxonomy for company tax submits. Here's the XBRL:
string xbrl = #"<xbrli:xbrl xml:lang='nl' xmlns:xbrli='http://www.xbrl.org/2003/instance' xmlns:link='http://www.xbrl.org/2003/linkbase' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:bd-alg='http://www.nltaxonomie.nl/8.0/basis/bd/items/bd-algemeen' xmlns:xbrldi='http://xbrl.org/2006/xbrldi' xmlns:bd-dim-dom='http://www.nltaxonomie.nl/8.0/basis/bd/domains/bd-domains' xmlns:bd-dim-dim='http://www.nltaxonomie.nl/8.0/domein/bd/axes/bd-axes' xmlns:bd-bedr='http://www.nltaxonomie.nl/8.0/basis/bd/items/bd-bedrijven' xmlns:iso4217='http://www.xbrl.org/2003/iso4217'>
<link:schemaRef xlink:type='simple' xlink:href='http://www.nltaxonomie.nl/8.0/report/bd/entrypoints/bd-rpt-vpb-aangifte-2013.xsd' xlink:arcrole='http://www.w3.org/1999/xlink/properties/linkbase'/>
<xbrli:context id='c1'>
<xbrli:entity>
<xbrli:identifier scheme='www.belastingdienst.nl/identificatie'>800030357</xbrli:identifier>
</xbrli:entity>
<xbrli:period>
<xbrli:startDate>2013-07-01</xbrli:startDate>
<xbrli:endDate>2014-06-01</xbrli:endDate>
</xbrli:period>
<xbrli:scenario>
<xbrldi:explicitMember dimension='bd-dim-dim:PartyDimension'>bd-dim-dom:Declarant</xbrldi:explicitMember>
</xbrli:scenario>
</xbrli:context>
<xbrli:context id='c2'>
<xbrli:entity>
<xbrli:identifier scheme='www.belastingdienst.nl/identificatie'>800030357</xbrli:identifier>
</xbrli:entity>
<xbrli:period>
<xbrli:instant>2014-06-01</xbrli:instant>
</xbrli:period>
<xbrli:scenario>
<xbrldi:explicitMember dimension='bd-dim-dim:TimeDimension'>bd-dim-dom:End</xbrldi:explicitMember>
<xbrldi:explicitMember dimension='bd-dim-dim:PartyDimension'>bd-dim-dom:Declarant</xbrldi:explicitMember>
</xbrli:scenario>
</xbrli:context>
<xbrli:unit id='u1'>
<xbrli:measure>iso4217:EUR</xbrli:measure>
</xbrli:unit>
<bd-alg:SoftwarePackageName contextRef='c1'>SoftwareNaame</bd-alg:SoftwarePackageName>
<bd-alg:SoftwarePackageVersion contextRef='c1'>V1</bd-alg:SoftwarePackageVersion>
<bd-alg:TaxReturnMessageType contextRef='c1'>81</bd-alg:TaxReturnMessageType>
<bd-bedr:AssetsTotalAmountFiscal contextRef='c2' decimals='INF' unitRef='u1'>0</bd-bedr:AssetsTotalAmountFiscal>
<bd-bedr:BalanceProfitCalculationForTaxPurposesFiscal contextRef='c1' decimals='INF' unitRef='u1'>0</bd-bedr:BalanceProfitCalculationForTaxPurposesFiscal>
</xbrli:xbrl>";
I use the following code to load the XSD and validate the document:
var doc = XDocument.Parse(xbrl);
var xmlReader = XmlReader.Create("http://www.nltaxonomie.nl/8.0/report/bd/entrypoints/bd-rpt-vpb-aangifte-2013.xsd");
var schema = XmlSchema.Read(xmlReader,
(sender, e) => { throw e.Exception; });
var set = new XmlSchemaSet();
set.Add(schema);
set.Compile();
doc.Validate(set, (sender, e) =>
{
throw new Exception("document validation failed: " + e.Message);
});
This produces the following error message:
document validation failed: The element 'xbrl' in namespace 'http://www.xbrl.org/2003/instance' has invalid child element 'SoftwarePackageName' in namespace 'http://www.nltaxonomie.nl/8.0/basis/bd/items/bd-algemeen'. List of possible elements expected: 'item, tuple, context, unit' in namespace 'http://www.xbrl.org/2003/instance' as well as 'footnoteLink' in namespace 'http://www.xbrl.org/2003/linkbase'.
Apparantly SchemaSet.Compile fails to find all the related XSD's (direct link to the main XSD here). I've been trying different ways of loading the schema and parsing the document for hours now, but I'm not sure how to solve this problem.
I have also tried to read the document with Gepsio. Gepsio loads the document, but doesn't find any facts in the document, so it looks like the structure of the Dutch taxonomy schema is the problem here.
Your XML instance does not validate with that schema. Perhaps it will validate with another schema which imports it, or perhaps you need to create a new schema which imports all the schemas you need.
The problem is that these elements, placed at top level below root, at the end of your file:
<bd-alg:SoftwarePackageName contextRef='c1'>SoftwareNaame</bd-alg:SoftwarePackageName>
<bd-alg:SoftwarePackageVersion contextRef='c1'>V1</bd-alg:SoftwarePackageVersion>
<bd-alg:TaxReturnMessageType contextRef='c1'>81</bd-alg:TaxReturnMessageType>
<bd-bedr:AssetsTotalAmountFiscal contextRef='c2' decimals='INF' unitRef='u1'>0</bd-bedr:AssetsTotalAmountFiscal>
<bd-bedr:BalanceProfitCalculationForTaxPurposesFiscal contextRef='c1' decimals='INF' unitRef='u1'>0</bd-bedr:BalanceProfitCalculationForTaxPurposesFiscal>
are not allowed, according to the schema.
If you believe they should be allowed, probably you are not using the correct schema.
If your application can use a derived type, a solution would be to create a new schema which imports the schema you need, and defines a new root (in a new namespace) which allows the extra elements. If the types in the original schema are exposed, you can also try to redefine the root type in the same namespace.
I have a C# Web Service that is serializing my simple class:
[Serializable]
[XmlInclude(typeof(Bitmap))]
[XmlTypeAttribute(Namespace = "http://tempuri.org/")]
public class Class1
{
private static Bitmap _myImage = new Bitmap(#"C:\WebApplication1\ClassLibrary1\Untitled.png");
public Bitmap MyImage
{
get { return _myImage; }
set
{
_myImage = value;
}
}
}
Here's the asmx.cs code that does the serialization:
[WebMethod]
public string HelloWorld()
{
var c = new Class1();
XmlSerializer serializer = new XmlSerializer(typeof(Class1));
return XMLSerializer(c);
}
public string XMLSerializer(object pObject)
{
try
{
XmlSerializer xs = new XmlSerializer(pObject.GetType());
using (StringWriter stream = new StringWriter())
{
xs.Serialize(stream, pObject);
stream.Flush();
return stream.ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
Looks prety straight forward. However, the XML generated by the XmlSerializer is producing and error when I try to DeSerialize it.
{"There is an error in XML document (5, 5)."}
{"Parameter is not valid."}
When I try to load the generated XML into IE I get this error.
Switch from current encoding to specified encoding not supported. Error processing resource 'file:///C:/Users/mhall15/Deskt...
<?xml version="1.0" encoding="utf-16"?>
Here's the generated XML:
<?xml version="1.0" encoding="utf-16"?>
<Class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyImage xmlns="http://tempuri.org/">
<Palette />
</MyImage>
</Class1>
Any ideas what's going on?
During the serialization, replace "encoding="utf-16" with "encoding="utf-8"" and that will cut it. The source of the problem - I'm not sure, but I've ran into it numerous times, and that's how I dealt with it.
That's how to deal with the IE issue.
The deserialization should be amongst these lines. I'm posting the kind of arbitrary code I normally use:
public static object DeserializeFromXML<T>(string _input)
{
object _temp = Activator.CreateInstance<T>();
Type expected_type = _temp.GetType();
_temp = null;
XmlSerializer serializer = new XmlSerializer(expected_type);
StringReader stringWriter = new StringReader(_input);
object _copy = serializer.Deserialize(stringWriter);
return _copy;
}
In the above example, I'm using templating for reusability sake. You should be able to call the method by saying DeserializeFromXML < Class1 >(_xml_input) where xml input is the string. That will force the compiler to use the definition of the given class to deserialize the XML input. That way you wouldn't even have to change the encoding in the serialization. If it's also a case where you may or may not know the data type to deserialize with, you can use a strategy design pattern where you register the root type of the XML with it's associated generic type. Later on you can reference that registry and arbitrarily deserialize any XML input as long as the root type is registered. It's a trick i normally use as well. If more is needed on this, let me know, and I'll explain in detail.
In addition,if you are running IE 9, the new update to IE 9 makes it difficult to view XML. Press F12 - go to developer tools and change your browser mode to run as IE 8 instead of IE 9.