Convert XML String to Object
You need to use the xsd.exe
tool which gets installed with the Windows SDK into a directory something similar to:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
And on 64-bit computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin
And on Windows 10 computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
On the first run, you use xsd.exe
and you convert your sample XML into a XSD file (XML schema file):
xsd yourfile.xml
This gives you yourfile.xsd
, which in a second step, you can convert again using xsd.exe
into a C# class:
xsd yourfile.xsd /c
This should give you a file yourfile.cs
which will contain a C# class that you can use to deserialize the XML file you're getting - something like:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));
Should work pretty well for most cases.
Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);
or use a StringReader:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);
Converting XML to C# object
For such problem, i would always choose using XmlSerializer.
Use this classes:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace classes
{
[XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
public class Order
{
public int OrderID { get; set; }
public string OrderStatus { get; set; }
}
[XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
public class OrderArray
{
public List<Order> Orders { get; set; }
}
[XmlRoot(Namespace = "urn:ebay:apis:eBLBaseComponents")]
public class GetOrdersResponse
{
public string Timestamp { get; set; }
public string Ack { get; set; }
public string Version { get; set; }
public string Build { get; set; }
public OrderArray OrderArray { get; set; }
}
}
Then Deserialize to your object:
XmlSerializer serializer = new XmlSerializer(typeof(GetOrdersResponse ));
using (TextReader reader = new StringReader(xmlResult))
{
GetOrdersResponse result = (GetOrdersResponse) serializer.Deserialize(reader);
}
int id=result.OrderArray.Orders.First().OrderID; //this will return ID of first object in Orders list.
Convert xml string to Java object
JAXB is the Java standard (JSR-222) for converting objects to/from XML. The following should help:
Unmarshalling from a String
You will need to wrap the String
in an instance of StringReader
before your JAXB impl can unmarshal it.
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);
Different Field and XML Names
You can use the @XmlElement
annotation to specify what you want the name of the element to be. By default JAXB looks at properties. If you wish to base the mappings on the fields then you need to set @XmlAccessorType(XmlAccessType.FIELD)
.
@XmlElement(name="count")
private int size;
Namespaces
The @XmlRootElement
and @XmlElement
annotations also allow you to specify namespace qualification where needed.
@XmlRootElement(namespace="http://www.example.com")
public class Response {
}
For More Information
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
- http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
- http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
Convert xml string different objects
var yourXML = @"<ProjectDetails>
<Product>
<ProductId>1</ProductId>
<ProductName>Product 1</ProductName>
</Product>
<Owner>
<OwnerId>1</OwnerId>
<OwnerName>Owner 1</OwnerName>
</Owner>
<Master>
<MasterId>1</MasterId>
<MasterName>Master 1</MasterName>
</Master>
</ProjectDetails>"
XmlSerializer serializer = new XmlSerializer(typeof(ProjectDetails));
using (TextReader reader = new StringReader(yourXML)) {
ProjectDetails result = (ProjectDetails) serializer.Deserialize(reader);
}
Or if you wish to deserialize Product
, Owner
, Master
independently, replace ProjectDetails
with the type you are deserializing. Or create a generic helper function to deserialize any type. (see https://stackoverflow.com/a/3187539/6419909)
This is known as deserializing an object, and in your case XML deserialization. See How to deserialize xml to object for further discussion.
Related Topics
How to Create Linq Expression Tree to Select an Anonymous Type
Get String Between Two Strings in a String
Ipc Mechanisms in C# - Usage and Best Practices
What Does "Use of Unassigned Local Variable" Mean
How to Get the List of Open File Handles by Process in C#
Deserialize Json to C# Classes
.Net Process.Start Default Directory
Do You Need to Dispose of Objects and Set Them to Null
Execute Powershell Script from C# With Commandline Arguments
Best Practice For Forcing Garbage Collection in C#
Can Attributes Be Added Dynamically in C#
String Output: Format or Concat in C#
Selenium C# Webdriver: Wait Until Element Is Present
How to Have an Auto Incrementing Version Number (Visual Studio)