Parse JCR XML export in C# - c#

I received some XML files from a customer that I need to process in C#. Looking at the structure and doing some googleing it seems that this content has been exported from JCR (I haven't worked with this at all so I might be wrong).
The structure looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<sv:node xmlns:sv="http://www.jcp.org/jcr/sv/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" sv:name="foodtruck-gruener-sepp">
<sv:property sv:name="jcr:primaryType" sv:type="Name">
<sv:value>mgnl:Event</sv:value>
</sv:property>
<sv:property sv:name="jcr:mixinTypes" sv:type="Name" sv:multiple="true">
<sv:value>mgnl:hasVersion</sv:value>
</sv:property>
<sv:property sv:name="jcr:uuid" sv:type="String">
<sv:value>6371704f-1cc4-4ab9-9298-43c9dd4f79ab</sv:value>
</sv:property>
<sv:property sv:name="name" sv:type="String">
<sv:value>user name</sv:value>
</sv:property>
<sv:property sv:name="email" sv:type="String">
<sv:value>info#somedomain.com</sv:value>
</sv:property>
</sv:node>
How would I go about parsing this? Can this be done by just using XMLElementAttribute with XmlSerializer?

The code below uses xml linq and puts results into a dictionary. The code does not parse the xml Type attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement node = doc.Root;
XNamespace sv = node.GetNamespaceOfPrefix("sv");
Dictionary<string, string> dict = doc.Descendants(sv + "property")
.GroupBy(x => (string)x.Attribute(sv + "name"), y => (string)y.Element(sv + "value"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}

have to create a class with the same type of XML, that can be generated through visual studio Edit> Paste Special to deserialize it.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.jcp.org/jcr/sv/1.0")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.jcp.org/jcr/sv/1.0", IsNullable = false)]
public partial class node
{
private nodeProperty[] propertyField;
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("property")]
public nodeProperty[] property
{
get
{
return this.propertyField;
}
set
{
this.propertyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.jcp.org/jcr/sv/1.0")]
public partial class nodeProperty
{
private string valueField;
private string nameField;
private string typeField;
private bool multipleField;
private bool multipleFieldSpecified;
/// <remarks/>
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public bool multiple
{
get
{
return this.multipleField;
}
set
{
this.multipleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool multipleSpecified
{
get
{
return this.multipleFieldSpecified;
}
set
{
this.multipleFieldSpecified = value;
}
}
}

Related

Adding namescpace prefix to XML

I have a number of POCO classes that are generating the required XML structure for serializtion to be passed as return in a SOAP WS. In selected elements I need to add namespace prefix/ alais to the elements. Is this possible? If yes how please?
POCO Classes
public partial class ValueTable
{
private List<ValueTableColumn> headerField;
private row[] rowField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("column", IsNullable = false)]
public List<ValueTableColumn> header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
/// <remarks/>
[XmlElement]
public row[] row
{
get
{
return this.rowField;
}
set
{
this.rowField = value;
}
}
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class row
{
private rowField[] fieldField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("field")]
public rowField[] field
{
get
{
return this.fieldField;
}
set
{
this.fieldField = value;
}
}
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class rowField
{
private string textField;
/// <remarks/>
public string text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
}
Sample XML with required namespace prefixes/alias
<v21:row>
<v21:field>
<v21:text>ID-1005896</v21:text>
</v21:field>
<v21:field>
<v21:text>Smith</v21:text>
</v21:field>
<v21:field>
<v21:text>64AF6547DDSEE</v21:text>
</v21:field>
</v21:row>
Currently it is being returned with out the prefixes/alias.
I appreciate any help :)
something like this should work:
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
XmlSerializer serializer = new XmlSerializer(typeof(ValueTable));
XmlDocument doc = new XmlDocument();
XPathNavigator xPathNavigator = doc.CreateNavigator();
var nameSpaces = new XmlSerializerNamespaces();
nameSpaces.Add("yourPrefix", "http://your.namespace.com");
using (var xmlWriter = xPathNavigator.AppendChild())
{
serializer.Serialize(xmlWriter, valueTableObject, nameSpaces);
}

How to desalinize an xml and pass it through wcf service in c#

I have an xml as shown below and want to pass it as a response from wcf service.What i did is, i used Visual studio to generate c# classes from xml and then deserilize the xml with the classes generated from VS.Data is coming in Soap UI from WCF service but when i click validate in soap ui, it is throwing error
EDIT on 250320
Finally i reached to single error like
line 17: Invalid xsi:type qname: 'c:string' in element SITE_NAME#http://schemas.datacontract.org/2004/07/ITSM_GIS_NRMIntegration.BusinessObjects
c# code
namespace ITSM_GIS_NRMIntegration
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GisItsmService : IGisItsmService
{
Datatable dtcustomerSiteDtls = dtcustomerSiteDtls.AsEnumerable()
.OrderBy(x => x.Field<string>("CBCM_PARTY_ID"))
.ThenBy(x => x.Field<string>("CBCM_PARTY_NAME"))
.ThenBy(x => x.Field<string>("SERVICE"))
.ThenBy(x => x.Field<string>("SITENAME"))
.ThenBy(x => x.Field<string>("NODENAME"))
.CopyToDataTable();
XElement allSites = doc.Root;
foreach (var idGroup in dtcustomerSiteDtls.AsEnumerable().GroupBy(x => x.Field<string>("CBCM_PARTY_ID")))
{
XElement siteNode = new XElement("PARTY_SITE_NODES");
allSites.Add(siteNode);
siteNode.Add(new XElement("CBCM_PARTY_ID", idGroup.Key));
siteNode.Add(new XElement("CBCM_PARTY_NAME", idGroup.First().Field<string>("CBCM_PARTY_NAME")));
DataTable dtfilter = dtcustomerSiteDtls.Select("CBCM_PARTY_ID = '" + idGroup.Key.ToString() + "'").CopyToDataTable();
foreach (var service in dtfilter.AsEnumerable().GroupBy(x => x.Field<string>("SERVICE")))
{
XElement partyServices = new XElement("PARTY_SERVICES");
siteNode.Add(partyServices);
partyServices.Add(new XElement("SERVICE_NAME", service.Key));
XElement serviceSites = new XElement("SERVICE_SITES");
partyServices.Add(serviceSites);
foreach (var serviceSite in service.GroupBy(x => x.Field<string>("SITENAME")))
{
serviceSites.Add(new XElement("SITE_NAME", serviceSite.Key));
XElement siteNodes = new XElement("SITE_NODES");
serviceSites.Add(siteNodes);
string[] nodeNames = serviceSite.Select(x => x.Field<string>("NODENAME")).Distinct().ToArray();
foreach (string nodeName in nodeNames)
{
siteNodes.Add(new XElement("NODE_NAME", nodeName));
}
}
}
}
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
XmlSerializer myItemSerializer = new XmlSerializer(typeof(getCustomerSites));
using (var reader = doc.CreateReader())
{
sitedetailsResObj = (getCustomerSites)myItemSerializer.Deserialize(reader);
}
C# classes used to serialize
namespace ITSM_GIS_NRMIntegration.BusinessObjects
{
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getCustomerSites:ResponseBase
{
private getCustomerSitesPARTY_SITE_NODES[] pARTY_SITE_NODESField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PARTY_SITE_NODES")]
public getCustomerSitesPARTY_SITE_NODES[] PARTY_SITE_NODES
{
get
{
return this.pARTY_SITE_NODESField;
}
set
{
this.pARTY_SITE_NODESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODES
{
private uint cBCM_PARTY_IDField;
private string cBCM_PARTY_NAMEField;
private getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES[] pARTY_SERVICESField;
/// <remarks/>
public uint CBCM_PARTY_ID
{
get
{
return this.cBCM_PARTY_IDField;
}
set
{
this.cBCM_PARTY_IDField = value;
}
}
/// <remarks/>
public string CBCM_PARTY_NAME
{
get
{
return this.cBCM_PARTY_NAMEField;
}
set
{
this.cBCM_PARTY_NAMEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PARTY_SERVICES")]
public getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES[] PARTY_SERVICES
{
get
{
return this.pARTY_SERVICESField;
}
set
{
this.pARTY_SERVICESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES
{
private string sERVICE_NAMEField;
private getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES sERVICE_SITESField;
/// <remarks/>
public string SERVICE_NAME
{
get
{
return this.sERVICE_NAMEField;
}
set
{
this.sERVICE_NAMEField = value;
}
}
/// <remarks/>
public getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES SERVICE_SITES
{
get
{
return this.sERVICE_SITESField;
}
set
{
this.sERVICE_SITESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[KnownType(typeof(getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES))]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES
{
private object[] sITE_NAMEField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SITE_NAME", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("SITE_NODES", typeof(getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES))]
public object[] SITE_NAME
{
get
{
return this.sITE_NAMEField;
}
set
{
this.sITE_NAMEField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES
{
private string[] nODE_NAMEField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("NODE_NAME")]
public string[] NODE_NAME
{
get
{
return this.nODE_NAMEField;
}
set
{
this.nODE_NAMEField = value;
}
}
}
Error in SOAP UI is as shown below
An
Why aren't you using two properties instead of one?
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES
{
private object[] itemNamesField;
private object[] itemNodessField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SITE_NAME", typeof(string))]
public object[] ItemNames
{
get
{
return this.itemNamesField;
}
set
{
this.itemNamesField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("SITE_NODES", typeof(getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES))]
public object[] ItemNodes
{
get
{
return this.itemNodesField;
}
set
{
this.itemNodesField = value;
}
}
}
Below is the code to deserialize the xml. Linq is much faster to deserialize than the code below. So you have to decide if it is better to use your code or the code below. Usually I recommend if you have a schema (and the classes) and trying to get all the data it is better to use serialization. You are putting results into a datatable which I then recommend xml linq. I just want to so why I suggested to remove the base class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(getCustomerSites));
getCustomerSites sites = (getCustomerSites)serializer.Deserialize(reader);
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getCustomerSites //: ResponseBase
{
private getCustomerSitesPARTY_SITE_NODES[] pARTY_SITE_NODESField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PARTY_SITE_NODES")]
public getCustomerSitesPARTY_SITE_NODES[] PARTY_SITE_NODES
{
get
{
return this.pARTY_SITE_NODESField;
}
set
{
this.pARTY_SITE_NODESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODES
{
private uint cBCM_PARTY_IDField;
private string cBCM_PARTY_NAMEField;
private getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES[] pARTY_SERVICESField;
/// <remarks/>
public uint CBCM_PARTY_ID
{
get
{
return this.cBCM_PARTY_IDField;
}
set
{
this.cBCM_PARTY_IDField = value;
}
}
/// <remarks/>
public string CBCM_PARTY_NAME
{
get
{
return this.cBCM_PARTY_NAMEField;
}
set
{
this.cBCM_PARTY_NAMEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PARTY_SERVICES")]
public getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES[] PARTY_SERVICES
{
get
{
return this.pARTY_SERVICESField;
}
set
{
this.pARTY_SERVICESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICES
{
private string sERVICE_NAMEField;
private getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES sERVICE_SITESField;
/// <remarks/>
public string SERVICE_NAME
{
get
{
return this.sERVICE_NAMEField;
}
set
{
this.sERVICE_NAMEField = value;
}
}
/// <remarks/>
public getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES SERVICE_SITES
{
get
{
return this.sERVICE_SITESField;
}
set
{
this.sERVICE_SITESField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
//[KnownType(typeof(getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES))]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITES
{
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SITE_NAME", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("SITE_NODES", typeof(getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getCustomerSitesPARTY_SITE_NODESPARTY_SERVICESSERVICE_SITESSITE_NODES
{
private string[] nODE_NAMEField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("NODE_NAME")]
public string[] NODE_NAME
{
get
{
return this.nODE_NAMEField;
}
set
{
this.nODE_NAMEField = value;
}
}
}
}

How to deserialize XML document with inner tags and inner elements?

This is my XML file.
<getMetadata>
<Project Name="Doors_Demo">
<Module FullPath="/Doors_Demo/Test_Module2">
<Attributes>
<Attribute name="TableType" type="TableType" />
<Attribute name="TableTopBorder" type="TableEdgeType" />
</Attributes>
</Module>
</Project>
</getMetadata>
I want to deserialize the above XML
Below is my code:
[XmlRoot("getMetadata")]
public class RootClass
{
public Project element_Project;
[XmlElement("Project")]
public Project Project
{
get { return element_Project; }
set { element_Project = value; }
}
}
public class Project
{
public string name;
[XmlAttribute("Name")]
public string Id
{
get { return name; }
set { name = value; }
}
}
public static void Main(string[] args)
{
RootClass obj = new RootClass();
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (FileStream stream = new FileStream(#"E:\getMetadata(4).xml", FileMode.Open))
{
RootClass myxml = (RootClass)serializer.Deserialize(stream);
Console.WriteLine(myxml.Project.name);
}
}
I want to deserialize my XML into a list, I am not able to access all inner elements and attributes inside the root element.
I want details of module element and its inner elements and tags into list which can be accessed.
Here is a little trick to generate classes from your XML automatically.
First, create a new empty class, name it for example TempXml.
Copy your XML to the clipboard and open the new empty class you just created.
Go to Visual Studio Edit menu then Paste Special and Paste XML as Classes:
This will generate the following code:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getMetadata
{
private getMetadataProject projectField;
/// <remarks/>
public getMetadataProject Project
{
get
{
return this.projectField;
}
set
{
this.projectField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProject
{
private getMetadataProjectModule moduleField;
private string nameField;
/// <remarks/>
public getMetadataProjectModule Module
{
get
{
return this.moduleField;
}
set
{
this.moduleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModule
{
private getMetadataProjectModuleAttribute[] attributesField;
private string fullPathField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Attribute", IsNullable = false)]
public getMetadataProjectModuleAttribute[] Attributes
{
get
{
return this.attributesField;
}
set
{
this.attributesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string FullPath
{
get
{
return this.fullPathField;
}
set
{
this.fullPathField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModuleAttribute
{
private string nameField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
Which should work fine with the XmlSerializer class.
You can clean up a little bit the generated output by removing the empty remarks, changing the name of the classes to use camel case (in this case you need to specify the real element name in the attribute as you were doing in your question) or move the classes to different files.
Hope it helps.

C# XML Parsing with multiple nodes

I have a file that is formatted roughly like:
what i want to do is get the Type element then get the data for each source and output it to text fields.
Cant seem to get it working.`
What is the best way to parse this?
<Config>
<Type>8_Port_Switch</Type> `
<Inputs>
<Source_1>
<Source_1_Name>BobsPC</Source_1_Name>
<Source_1_Input>7</Source_1_Input>
</Source_1>
<Source_2>
<Source_2_Name>Office</Source_2_Name>
<Source_2_Input>4</Source_2_Input>
</Source_2>
<Source_3>
<Source_3_Name>Printer</Source_3_Name>
<Source_3_Input>3</Source_3_Input>
</Source_3>
</Config>
this file can be up to 32 ports. I want to use the type info to force a particular form to open then populate the form with the results of the read.
i have a label for each source and 2 text boxes for Name and Input that i want to populate
for example. I want to read the data and populate:
enter image description here
edit the information.
Then create a new xml doc and upload to the server. I can create with no issues. Its just reading it and passing it back into the fields.
Option 1
I think a clean approach will be to throw the contents of your XML into a DataSet and then bind your form's controls to the table. Here is an example to help you:
DataSet ds = new DataSet();
ds.readxml("XML File Path");
var bs = new BindingSource();
bs.DataSource = ds;
bs.DataMember = ds.table[0].tablename;
textBox1.DataBindings.Add("FirstName", bs, "Table Name");
textBox2.DataBindings.Add("FirstName", bs, "Table Name");
Option 2
You can use my answer here to create a C# class for your xml. Then deserialize the xml contents into the C# class. Once you have deserialized it into the C# class, you can work and manipulate the instance of the class. You can even bind the instance to your form. The form controls can change the contents of the instance like any C# class instance.
Once you are done, you can then serialize back to xml. Here is the class that was generated for your XML:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Config
{
private string typeField;
private ConfigInputs inputsField;
/// <remarks/>
public string Type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
public ConfigInputs Inputs
{
get
{
return this.inputsField;
}
set
{
this.inputsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigInputs
{
private ConfigInputsSource_1 source_1Field;
private ConfigInputsSource_2 source_2Field;
private ConfigInputsSource_3 source_3Field;
/// <remarks/>
public ConfigInputsSource_1 Source_1
{
get
{
return this.source_1Field;
}
set
{
this.source_1Field = value;
}
}
/// <remarks/>
public ConfigInputsSource_2 Source_2
{
get
{
return this.source_2Field;
}
set
{
this.source_2Field = value;
}
}
/// <remarks/>
public ConfigInputsSource_3 Source_3
{
get
{
return this.source_3Field;
}
set
{
this.source_3Field = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigInputsSource_1
{
private string source_1_NameField;
private byte source_1_InputField;
/// <remarks/>
public string Source_1_Name
{
get
{
return this.source_1_NameField;
}
set
{
this.source_1_NameField = value;
}
}
/// <remarks/>
public byte Source_1_Input
{
get
{
return this.source_1_InputField;
}
set
{
this.source_1_InputField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigInputsSource_2
{
private string source_2_NameField;
private byte source_2_InputField;
/// <remarks/>
public string Source_2_Name
{
get
{
return this.source_2_NameField;
}
set
{
this.source_2_NameField = value;
}
}
/// <remarks/>
public byte Source_2_Input
{
get
{
return this.source_2_InputField;
}
set
{
this.source_2_InputField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigInputsSource_3
{
private string source_3_NameField;
private byte source_3_InputField;
/// <remarks/>
public string Source_3_Name
{
get
{
return this.source_3_NameField;
}
set
{
this.source_3_NameField = value;
}
}
/// <remarks/>
public byte Source_3_Input
{
get
{
return this.source_3_InputField;
}
set
{
this.source_3_InputField = value;
}
}
}
Your xml had some errors and I had to fix them such as the closing tags were missing. Then I used the following code to change one thing and then resave it. It worked:
var serializer = new XmlSerializer(typeof(Config));
var reader = new StreamReader("StackQuestion.xml");
var result = serializer.Deserialize(reader) as Config;
reader.Close();
result.Inputs.Source_1.Source_1_Name = "CodingYoshi";
serializer.Serialize(new StreamWriter("StackQuestion.xml"), result);
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("Config").Select(x => new {
name = (string)x.Element("Type"),
type = x.Element("Inputs").Elements().Select(y => new
{
id = y.Name.LocalName,
name = (string)y.Elements().First(),
input = (int)y.Elements().Last()
}).ToList()
}).ToList();
}
}
}

XML parsing and returning as JSON

Please help me parse this file and get the output as JSON.
So far I am able to get the key (name) and Value (value) pair.
But I don't understand how to get the array inside this key-value pair.
New to XML and JSON and C#. Guru's please help..
<?xml version="1.0" encoding="US-ASCII"?>
<Information>
<first_name>Frank</first_name>
<last_name>Murphy</last_name>
<customer_support_url>google.com</customer_support_url>
<received_date>12/30/2013</received_date>
<customer_support_phone_number>(888)111-2222</customer_support_phone_number>
<employer_name>Google Inc</employer_name>
<label>Dependent Care</label>
<set_flag>0</set_flag>
<employee_id>11111</employee_id>
<employer_id>111</employer_id>
<claim_form_id>1234</claim_form_id>
<employer_url>For more information please go to: <a href=http://google.com>google.com</a></employer_url>
<tax>$1,500.00</tax>
<claim_form_id>1234</claim_form_id>
<claim_details>
<claim_form_id>1234</claim_form_id>
<amount_claimed>100</amount_claimed>
<expense_name>ChildCare</expense_name>
<service_date>2013-06-17</service_date>
<claim_status>Approved</claim_status>
<claim_status_reason/>
</claim_details>
<Location>Dublin</Location>
So far this is what I have done for testing purpose in a console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("input.xml");
// Declare your token Colelction Class
foreach (var keyvalue in doc.Root.DescendantNodes().OfType<XElement>().Select(x => new XElement("token", new XElement("name", x.Name), new XElement("value", x.Value))))
{
Console.WriteLine(keyvalue);
//Add name,value to token collection
}
// Convert it to json
//return
Console.ReadKey();
}
}
}
You can use Json.NET's JsonConvert.SerializeXmlNode() to convert XML to JSON easily :
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
string jsonText = JsonConvert.SerializeXmlNode(doc);
Result :
{
   "Information": {
      "first_name": "Frank",
      "last_name": "Murphy",
      "customer_support_url": "google.com",
      "received_date": "12/30/2013",
      "customer_support_phone_number": "(888)111-2222",
      "employer_name": "Google Inc",
      "label": "Dependent Care",
      "set_flag": "0",
      "employee_id": "11111",
      "employer_id": "111",
      "claim_form_id": [
         "1234",
         "1234"
      ],
      "employer_url": "For more information please go to: <a href=http://google.com>google.com<\/a>",
      "tax": "$1,500.00",
      "claim_details": {
         "claim_form_id": "1234",
         "amount_claimed": "100",
         "expense_name": "ChildCare",
         "service_date": "2013-06-17",
         "claim_status": "Approved",
         "claim_status_reason": null
      },
      "Location": "Dublin"
   }
}
First convert your XML to classes, in vs edit pasted special paste XML as classes gives this (ps you've missed the closing line in your xml )
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Information
{
private object[] itemsField;
private ItemsChoiceType[] itemsElementNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Location", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("claim_details", typeof(InformationClaim_details))]
[System.Xml.Serialization.XmlElementAttribute("claim_form_id", typeof(ushort))]
[System.Xml.Serialization.XmlElementAttribute("customer_support_phone_number", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("customer_support_url", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("employee_id", typeof(ushort))]
[System.Xml.Serialization.XmlElementAttribute("employer_id", typeof(byte))]
[System.Xml.Serialization.XmlElementAttribute("employer_name", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("employer_url", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("first_name", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("label", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("last_name", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("received_date", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("set_flag", typeof(byte))]
[System.Xml.Serialization.XmlElementAttribute("tax", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName
{
get
{
return this.itemsElementNameField;
}
set
{
this.itemsElementNameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class InformationClaim_details
{
private ushort claim_form_idField;
private byte amount_claimedField;
private string expense_nameField;
private System.DateTime service_dateField;
private string claim_statusField;
private object claim_status_reasonField;
/// <remarks/>
public ushort claim_form_id
{
get
{
return this.claim_form_idField;
}
set
{
this.claim_form_idField = value;
}
}
/// <remarks/>
public byte amount_claimed
{
get
{
return this.amount_claimedField;
}
set
{
this.amount_claimedField = value;
}
}
/// <remarks/>
public string expense_name
{
get
{
return this.expense_nameField;
}
set
{
this.expense_nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
public System.DateTime service_date
{
get
{
return this.service_dateField;
}
set
{
this.service_dateField = value;
}
}
/// <remarks/>
public string claim_status
{
get
{
return this.claim_statusField;
}
set
{
this.claim_statusField = value;
}
}
/// <remarks/>
public object claim_status_reason
{
get
{
return this.claim_status_reasonField;
}
set
{
this.claim_status_reasonField = value;
}
}
}
Then de-serialise the XML to c# objects
XmlSerializer serializer = new XmlSerializer(typeof(Information));
convert to JSon
string Json= JsonConvert.SerializeObject(ObjectInstance);

Categories