I am writing a method in c# that gets xml from web service with a lot of data that I do not need. I managed to select only tags that I need with this command:
var exchangeRateDataSet = xmlNew.Descendants("ExchangeRateDataSet");
Now I need to convert it to string so I can deserialize it and convert it to object of my class.
But, there is a problem. When i try to do this:
var toRead = exchangeRateDataSet.ToString();
I get this as a string, which of course isn't valid: System.Xml.Linq.XContainer+d__39
This is a piece of xml that I have:
``
<?xml version="1.0"?>
<ExchangeRateDataSet xmlns="">
<ExchangeRate xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" msdata:rowOrder="0" diffgr:id="ExchangeRate1">
<ExchangeRateListNumber>111</ExchangeRateListNumber>
<Date>14.06.2019</Date>
<CreateDate>14.06.2019</CreateDate>
<DateTo>31.12.4172</DateTo>
<ExchangeRateListTypeID>1</ExchangeRateListTypeID>
<CurrencyGroupID>2</CurrencyGroupID>
<CurrencyCode>978</CurrencyCode>
<CurrencyCodeNumChar>978</CurrencyCodeNumChar>
<CurrencyCodeAlfaChar>EUR</CurrencyCodeAlfaChar>
<CurrencyNameSerCyrl>Евро</CurrencyNameSerCyrl>
<CurrencyNameSerLat>Evro</CurrencyNameSerLat>
<CurrencyNameEng>Euro</CurrencyNameEng>
<CountryNameSerCyrl>ЕМУ</CountryNameSerCyrl>
<CountryNameSerLat>EMU</CountryNameSerLat>
<CountryNameEng>EMU</CountryNameEng>
<Unit>1</Unit>
<BuyingRate>117.6265</BuyingRate>
<MiddleRate>0.0000</MiddleRate>
<SellingRate>118.3343</SellingRate>
<FixingRate>0.000000</FixingRate>
</ExchangeRate>
<ExchangeRate xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" msdata:rowOrder="1" diffgr:id="ExchangeRate2">
<ExchangeRateListNumber>111</ExchangeRateListNumber>
<Date>14.06.2019</Date>
<CreateDate>14.06.2019</CreateDate>
<DateTo>31.12.4172</DateTo>
<ExchangeRateListTypeID>1</ExchangeRateListTypeID>
<CurrencyGroupID>3</CurrencyGroupID>
<CurrencyCode>36</CurrencyCode>
<CurrencyCodeNumChar>036</CurrencyCodeNumChar>
<CurrencyCodeAlfaChar>AUD</CurrencyCodeAlfaChar>
<CurrencyNameSerCyrl>Аустралијски долар</CurrencyNameSerCyrl>
<CurrencyNameSerLat>Australijski dolar</CurrencyNameSerLat>
<CurrencyNameEng>Australian Dollar</CurrencyNameEng>
<CountryNameSerCyrl>Аустралија</CountryNameSerCyrl>
<CountryNameSerLat>Australija</CountryNameSerLat>
<CountryNameEng>Australia</CountryNameEng>
<Unit>1</Unit>
<BuyingRate>71.9868</BuyingRate>
<MiddleRate>0.0000</MiddleRate>
<SellingRate>72.4200</SellingRate>
<FixingRate>0.000000</FixingRate>
</ExchangeRate>
``
To summarize, my question is how to convert this xml to object?
Any help would be appreciated. Thanks.
Related
using CsQuery;
namespace CSQuery
{
class Program
{
static void Main(string[] args)
{
var dom = CQ.Create(/*I am not sure what goes here*/);
//Not sure if this is the correct setup as well
CQ mf = dom["MANUFACTURER"];
CQ md = dom["MODEL"];
Console.WriteLine(mf);
Console.WriteLine(md);
Console.ReadKey();
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
--------------------------------------------------------
PARTS:
Title: Computer Parts
<ITEM>Motherboard</ITEM>
<MANUFACTURER>ASUS</MANUFACTURER>
<MODEL>P3B-F</MODEL>
<COST> 123.00</COST>
<ITEM>Video Card</ITEM>
<MANUFACTURER>ATI</MANUFACTURER>
<MODEL>All-in-Wonder Pro</MODEL>
<COST>160.00</COST>
<ITEM> Monitor </ITEM>
<MANUFACTURER>LG Electronics</MANUFACTURER>
<MODEL> 995E</MODEL>
<COST> 290.00</COST>
</PART></PARTS>
Above is my code I have written so far I am trying to extract the MANUFACTURER and MODEL from the sample given xml code. When I compile I get an error message saying source can not be found and I think it may be a problem with my setup and I am unclear on what exactly is suppose to go into my CQ.Create() as a parameter(I tried putting in the exact parts.xml file but that didn't help).
I want the output to be like this:
<Order xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:gml="example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd"
xsi:noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">
The code I am using to get this is :
xmlDocument.DocumentElement.SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
xmlDocument.DocumentElement.SetAttribute("xmlns:gml", "example.com");
xmlDocument.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlDocument.DocumentElement.SetAttribute("xsi:schemaLocation", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");
xmlDocument.DocumentElement.SetAttribute("xsi:noNamespaceSchemaLocation","http://www. xyz.co.uk/xmlorders3/lig_xml_orders.xsd");
But I am getting the output like this :
<Order xmlns:gml="example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd"
noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">
Please suggest me any other way to get the required output.
You should use another version of SetAttribute method:
xmlDocument.DocumentElement
.SetAttribute("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");
i found way out. it may not be the best way. the solution is :
string xmlString = xmlDocument.InnerXml.ToString(); xmlString= xmlString.Replace("schemaLocation", "xsi:schemaLocation"); xmlString= xmlString.Replace("noNamespaceSchemaLocation", "xsi:noNamespaceSchemaLocation"); xmlDocument.LoadXml(xmlString);
// now i have the xmlDocument as i required.
I want to create a simple XML file to store some settings that can be easily changed in a text editor. This is my XML file:
<connection>
<hostname>the.host.name</hostname>
<port>1000</port>
<database>theDbName</database>
</connection>
I am trying to use Linq to XML now to read that info into my program, but it gives me an error:
Could not find an implementation of the query pattern for source type 'System.Xml.Linq.XElement'. 'Select' not found.
My code is as follows:
XElement root = XElement.Load(".\\Resources\\Connection.xml");
string host = from el in root.Element("hostname") select el.Element("text");
XDocument xDoc = XDocument.Load(".\\Resources\\Connection.xml");
string host = (string)xDoc.Root.Element("hostname");
I think you're confused on how your XML structure should look and the way you read that XML with LinQ. First of all place your connection-element in a root called connections. Your XML looks like this now:
<?xml version="1.0" encoding="utf-8"?>
<connections>
<connection>
<hostname>the.host.name</hostname>
<port>1000</port>
<database>theDbName</database>
</connection>
</connections>
Now you can select the elements under that root and read all the data from it. Example code looks like following:
var root = XElement.Load(".\\Resources\\Connection.xml");
var connection = root.Elements("connection").FirstOrDefault();
if(connection != null)
{
var host = connection.Element("hostname").Value;
//do something with 'host'
}
Update:
If you don't want a root element 'connections', you can omit it and use following code to read the XML:
var xmlDoc = XDocument.Load("G:\\Connection.xml");
var connection = xmlDoc.Descendants("connection").FirstOrDefault();
if(connection != null)
{
var host = connection.Element("hostname").Value;
//do something with 'host'
}
I've been trying to read an xml file from an external source to get it into a dataset. I've taken the schema and compiled my class through xsd and have loaded it into the solution.
my xml:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<CAMDealerManifest AssetURL="http://www.the placewherethefilelives.com/CAMPublic/d98c8185/" DealerCode="41065" DealerGuid="bc0d0bc8-b37b-11e3-a345-ac162dbc18f8" DealerName="Ron Hibbard Toyota" ManifestId="13" ManifestURL="http://www.toyota.com/CAMPublic/d/41065-bc0d0bc8.xml" Path="41065-bc0d0bc8" ProviderId="1011" WebsiteVendorName="WorldDealer">
<CAMCampaigns count="15" dateTime="2014-09-16T17:18:40.877-07:00">
<CAMCampaign ManifestId="13" endDate="2014-12-31T11:59:59-08:00" flightDates="08/01/14 - 12/31/14" geography="National" groupName="National" id="68" name="National - Corolla Style Elevated" priority="0" required="false" startDate="2014-08-01T12:00:00-07:00">
<CAMCreative SubGroup="Corolla Style Elevated" Id="49" Name="National - Corolla Style Elevated" ImageAltText="Toyota's national banner for the stylish 2014 Corolla" ImageSearchTerms="Toyota, 2014 Corolla, Style Elevated, New Heights" Link="New Inventory" Model="Corolla" MonthYear="08-2014" Priority="3" Required="false">
<CAMCreativeSource CAMAssetCount="1" Height="409" Width="990" MediaBinAssetId="0E1C886A-C5CE-4409-AD36-7070D614A7A6" MediaBinFileName="03-14_01_2014_nat-style-elevated_990x409_0000000460_corolla_o_xta.jpg">
<CAMAsset Path="National/Corolla-Style-Elevated/National---Corolla-Style-Elevated/990/409/" Id="1273" Name="08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta.jpg" Height="409" Width="990" assetType="JPG" Guid="b9f4d3cd-fefd-4ff3-b209-338f409e551c" Md5Hex="3e328dc32a2db9fc1f3d6a2167d3e5d2">
<CAMTracking>
<SiteCatalyst version="1.0">
<Click tmsomni.events="event28" tmsomni.products=";08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta;;;event28=1"/>
<Impression tmsomni.events="event29" tmsomni.products=";08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta;;event29=1;evar43=img|evar61=corolla|evar54=o|evar49={$CAM_PAGE_POSITION}"/>
</SiteCatalyst>
</CAMTracking>
</CAMAsset>
</CAMCreativeSource>
</CAMCreative>
</CAMCampaign>
</CAMCampaigns>
<CAMExpiredCampaigns count="0" dateTime="2014-09-16T17:18:40.873-07:00"/>
</CAMDealerManifest>
I can't seem to get this xml to list or put into a dataset. I'm new to deserializing xml and could use some assistance.
Simply call ReadXml with the path to the file:
var dataSet = new DataSet();
dataSet.ReadXml(string PathToFile);
Works pretty well; will even create all the relations (notice CAMDealerManifestId in the screenshot).
Your file went in with only a modification to the XML declaration -- had to change standalone value from true to yes:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
If you're reading this in as a string, you could do something like this:
var xmlString = HoweverYouGetTheString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
xmlString[0] = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
using (var reader = new System.IO.StringReader(String.Join("\r\n", xmlString)))
{
dataSet.ReadXml(reader);
}
I'm patching together a C# Webservice which reads predefined SOAP responses from XML files. We're using this to mock a productive web service. The XML files contain the nodes directly child to ''. However, my current code adds a node to '', thus resulting in a wrong format.
What I got:
<soap:Body>
<Security_AuthenticateResponse xmlns="http://xml.tempuri.com/">
<Security_AuthenticateReply xmlns="http://xml.tempuri.com/VLSSLR_06_1_1A">
<processStatus>
...
</processStatus>
</Security_AuthenticateReply>
</Security_AuthenticateReply>
</soap:Body>
What we need:
<soap:Body>
<Security_AuthenticateReply xmlns="http://xml.tempuri.com/VLSSLR_06_1_1A">
<processStatus>
...
</processStatus>
</Security_AuthenticateReply>
</soap:Body>
My code:
[SoapDocumentMethod(Action = "http://webservices.amadeus.com/1ASIWABOAAI/VLSSLQ_06_1_1A",
RequestNamespace = "http://xml.amadeus.com/VLSSLQ_06_1_1A",
RequestElementName = "Security_Authenticate",
ResponseNamespace = "http://xml.amadeus.com/VLSSLR_06_1_1A",
ResponseElementName = "Security_AuthenticateReply")]
[WebMethod]
[return: XmlAnyElement]
[SoapHeader("sessionId", Direction = SoapHeaderDirection.Out)]
public XmlDocument Security_Authenticate()
{
.. some file magic here ...
XmlDocument rp = getFile("Security_AuthenticateReply.xml");
return rp;
}
I'm hoping for some directive which tells C# to drop one of the nodes. As an alternative, I guess I'll have to extract all child nodes and return those.