I have to read the XML:
<items>
<item>
<prop1>value1</prop1>
<prop2>value2</prop2>
<prop3>value3</prop3>
</item>
<item>
<prop1>value1</prop1>
<prop2>value2</prop2>
<prop3>value3</prop3>
</item>
</items>
And put the values into a List<CLASS>.
Some options:
Use XMLSerializer to deserialize to a List
Use XMLDocument to read each item using SelectNodes with XPath and put the values into a List
Use XMLReader to read each node and put the values into a List
Other option...
By far the fastest that I have seen is to use XSD.exe to create an XSD and Class to go with it, then use serialization.
Another option would be to use LinqToXml.
If you're in dotnet, install the WCF starter pack. Then you'll have an option "Paste XML as Types", so you can cut the XML you're looking to serialize into the clipboard and paste it into code as a serializable type. Then you can just serialize the XML and get the values through the class.
Related
Below Example How can Get "Airtel" and "145" Values, because my Client Has given this type XML Response
So How Can I Get both Values
<item item="Campaign name" type="string">Airtel</item>
<item item="Daily Limit" type="number">145</item>
As per the comment, we would need to see the full XML to give you a more complete answer. But you have 3 real options :
XMLReader. Probably not what you want as it's forward only and involves a lot of manual parsing.
XMLDocument. Not a bad option if you only want limited amount of notes and want their values and don't want to deserialize the entire XML doc.
XMLSerializer. Good if you want to deserialize the entire object straight from XML to class without you having to do a heck of a lot.
If you edit your question to include the full XML doc, then I can give you a more complete answer or you can read about your options for parsing XML here : https://dotnetcoretutorials.com/2020/04/23/how-to-parse-xml-in-net-core/
I have the following scenarios for output from a web service (the output's type is string, but the content of the string is XML).
When the service didn't succeed the output is:
<root>
<exec_id>2053c884-beec-4c33-af64-bce8c4a8601c</exec_id>
<ERROR_CODE>-13</ERROR_CODE>
<OUTPUT_XML>Policy GO Period is mistaken (Mar 9 2016 8:43PM, Mar 6 2017 11:59PM)</OUTPUT_XML>
</root>
When the service returns something, the response is:
<root>
<exec_id>9a506024-8996-4f17-bcc4-a4616b2c28da</exec_id>
<ERROR_CODE>0</ERROR_CODE>
<OUTPUT_XML>
<root>
<ProposalNo>000334374</ProposalNo>
<InsPremium>225.40</InsPremium>
<InsDuePremium>241.310</InsDuePremium>
<FeesInfo>
<Fee>
<PaymentDate>2016-03-09T16:08:34.613</PaymentDate>
<FeeSum>241.31</FeeSum>
<FeeSumCurCode>BGN</FeeSumCurCode>
<AgencyCode>001</AgencyCode>
</Fee>
</FeesInfo>
<ERROR_MSG>Успешно изпълнена процедура</ERROR_MSG>
</root>
</OUTPUT_XML>
</root>
So, based on this, I created a base class that contains exec_id and ERROR_CODE, because they are common for all responses. Now the problem is OUTPUT_XML, because it's a different object every time so I have a successor class for each method of the service. The problem is when the service returns an error message in the OUTPUT_XML. My question is how to handle this in the best possible way?
Is the service under your control? (Not sure if that's a constraint.)
There are no attributes that will allow out-of-the-box deserialization of the XML in both scenarios above. You could write some custom serialization but that would be overkill.
If the service is yours then you could define a response class and serialize that. If you can serialize it then you can deserialize it. Then in your response XML you have an element for the output and an element for an error message, not one element which may contain either. The contents of XML should be more predictable. That's why we use schemas. But using a class to serialize and deserialize accomplishes the same thing. The XML will be predictable.
You could also get the InnerXml property of the <OUTPUT_XML> node and if it begins with <root> then deserialize that string is a separate XML document. That's logical since that's what they're actually giving you - an XML document as string inside of an XML document.
Or, as was said, if the error code is reliable indicator then you could just read that first.
I'm trying to import XML files into my C# code.
I would like to access these data like a dictionnary element.
Example:
// XML:
<root>
<node>
<value1>
</value1>
<value2>
<properties>
</properties>
</value2>
<randomnode>
<blabla>X</blabla>
</randomnode>
</node>
</root>
// C#:
values["root"]["node"]["randomnode"]["blabla"] == "X" // true
Is there any way to do this?
As far as I've searched, I could only get a dictionnary using XElements, but it was only 2-dimensions and I had to specify names and values as attributes in the XML file.
Thanks for answering!
I suggest you to use dynamic type for this. See here for code. Or here.
I've used sharpSerializer for that. Heres a pretty good walkthrough:
XML Serialization of Generic Dictionary, Multidimensional Array, and Inherited Type, with sharpSerializer .NET
I'm trying to serialize an XML file returned from a SOAP API service. The issue is that they have defined an array of objects as such:
<soap_xml>
...
<item __array="true">
<some_property>text here<some_property/>
</item>
<item>
<some_property>text here<some_property/>
</item>
...
</soap_xml>
Is there anyway to use the XmlSerializer to condense this down into an array when deserializing this XML file, or will I have to process the entire XML file manually. I'm not keen on having to process the XML manually, since it has over 100 different properties/fields, but if there is no other solution, then I'll have to use a XMLReader and write a custom serializer.
Also, asking the API provider to change the format of the returned XML is out of the question.
You'll need to define a class that follows the schema of the XML file - do you have a schema from the API provider? If so, you could use xsd.exe to generate a class file that can load it.
Alternatively, you'll need to annotate your own class with the appropriate XML attributes that follows the format.
I need to embed an entire well-formed xml document within another xml document. However, I would rather avoid CDATA (personal distaste) and also I would like to avoid the parser that will receive the whole document from wasting time parsing the embedded xml. The embedded xml could be quite significant, and I would like the code that will receive the whole file to treat the embedded xml as arbitrary data.
The idea that immediately came to mind is to encode the embedded xml in base64, or to zip it. Does this sound ok?
I'm coding in C# by the way.
You could convert the XML to a byte array, then convert it to binary64 format. That will allow you to nest it in an element, and not have to use CDATA.
The W3C-approved way of doing this is XInclude. There is an implementation for .Net at http://mvp-xml.sourceforge.net/xinclude/
Just a quick note, I have gone the base64 route and it works just fine but it does come with a stiff performance penalty, especially under heavy usage. We do this with document fragments upto 20MB and after base64 encoding they can take upwards of 65MB (with tags and data), even with zipping.
However, the bigger issue is that .NET base64 encoding can consume up-to 10x the memory when performing the encoding/decoding and can frequently cause OOM exceptions if done repeatedly and/or done on multiple threads.
Someone, on a similar question recommended ProtoBuf as an option, as well as Fast InfoSet as another option.
Depending on how you construct the XML, one way is to not care about it and let the framework handle it.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><helloworld></helloworld>");
string xml = "<how><are><you reply=\"i am fine\">really</you></are></how>";
doc.GetElementsByTagName("helloworld")[0].InnerText = xml;
The output will be something like a HTMLEncoded string:
<?xml version="1.0" encoding="utf-8"?>
<helloworld><how><are><you
reply="i am fine">really</you></are></how>
</helloworld>
I would encode it in your favorite way (e.g. base64 or HttpServerUtility::UrlEncode, ...) and then embed it.
If you don't need the xml declaration (first line of the document), just insert the root element (with all childs) into the tree of the other xml document as a child of an existing element. Use a different namespace to seperate the inserted elements.
It seems that serialization is the recommended method.
Can't you use XSLT for this? Perhaps using xsl:copy or xsl:copy-of? This is what XSLT is for.
I use Comments for this :
<!-- your xml text -->
[EDITED]
If the embedded xml with comments, replace it with a different syntax.
<?xml version="1.0" encoding="iso-8859-1" ?>
<xml>
<status code="0" msg="" cause="" />
<data>
<order type="07" user="none" attrib="..." >
<xmlembeded >
<!--
<?xml version="1.0" encoding="iso-8859-1" ?>
<xml>
<status ret="000 "/>
<data>
<allxml_here />
<!** embedeb comments **>
</data>
<xml>
-->
</xmlembeded >
</order>
<context sessionid="12345678" scriptname="/from/..." attrib="..." />
</data>
</xml>