Convert object model to XML - c#

Good day guys, How can i convert an object model to an xmldocument. this is my object:
var profile = new ProfileModel()
{
xh="aa",
FirstName = "wolverine",
LastName = "wolverine2",
PhoneNumber = "66332214477",
Email = "wolverine#wolverine.com",
SourceSystem = "TY",
ID = "ty1002224"
};
right now I'm doing it manually like this:
XDocument doc = new XDocument(new XElement("aa",
new XElement("FirstName","wolverine2"),
new XElement("LastName", "wolverine"),
new XElement("PhoneNumber", "66332214477"),
new XElement("Email", "wolverine#wolverine.com"),
new XElement("SourceSystem", "TY"),
new XElement("ID", "ty1002224")
));
but i want something more generic so i could use it to all of my object. Also, I have a case that I have a list of ProfileModel and need to convert it to xmldocument.
EDIT:
I want the output to be plain xdocument:
<aa>
<FirstName>wolverine2</FirstName>
<LastName>wolverine</LastName>
<PhoneNumber>66332214477</PhoneNumber>
<Email>wolverine#wolverine.com</Email>
<SourceSystem>TY</SourceSystem>
<ID>ty1002224</ID>
</aa>

Have a look at the XmlSerializer class
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

By using the amazing XDocument class. This will use reflection and serialize all the properties.
// in System.Xml.Linq
XDocument doc = new XDocument();
using (var writer = doc.CreateWriter())
{
// write xml into the writer
var serializer = new DataContractSerializer(objToSerialize.GetType());
serializer.WriteObject(writer, objectToSerialize);
}
Console.WriteLine(doc.ToString());
Source: How do I serialize an object into an XDocument?

Related

How to avoid the ROOT Element when parsing from XML to JSON in C#

I am trying to create a JSON from an xml using JSON.NET
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson); //xmlPerson is the xml from above
JObject personDefinition = JObject.Parse(JsonConvert.SerializeObject(docPerson));
Tasks.personDefinition = personDefinition["personDefinition"];
OUTPUT JSON
"person":{"person":[{"personId":"1","firstName":"Name1","lastName":"lastName1"}, {"personId":"3","firstName":"Name2","lastName":"lastName2"}]}
I don't need the outer person and just need the following json
REQUIRED JSON
"person":[{"personId":"1","firstName":"1","lastName":"Weight"},{"personId":"3","firstName":"4","lastName":"Pulse Ox"}]}
I have tried using the .first method however it is throwing an error. Can anyone suggest on how to strip the root from the output json
JSON.Net has a SerializeXmlNode() method that can do exactly what you want. Simply pass true to the omitRootObject parameter.
Observe:
string xmlPerson = #"<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson);
string json = JsonConvert.SerializeXmlNode(docPerson, Formatting.None, true);
Console.WriteLine(json);
Output:
{"Person":[{"name":"Nicolas","age":"22"},{"name":"Pankaj","age":"25"}]}
string xml = "<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person[]), new XmlRootAttribute("PersonDefinition"));
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
using (TextReader reader = new StringReader(xml))
{
Person[] people = xmlSerializer.Deserialize(reader) as Person[];
string json = jsonSerializer.Serialize(new Person());
}
Use some kind of variation of this.

How to remove the XML declaration when using LINQ to XML?

i have a LINQ query like this, i need to remove the XML Declaration tag which is getting added automatically.
var cubbingmessagexml = new XDocument(
new XElement("MESSAGE", new XAttribute("ID", "CUB"),
new XElement("RECORD", new XAttribute("STORENO", cubing.StoreID),
new XAttribute("TPNB", cubing.ProductCode),
new XAttribute("QUANTITY", cubing.Quantity),
new XAttribute("CUBINGTIME", cubing.CubingDateTime.ToString("yyyyMMddHHmmss")),
new XAttribute("SHELFFACING", cubing.ShelfFacing)
)));
xml = cubbingmessagexml.ToString();
pls help
I dont want to save the XML file, just need to return the XML as a string
If you are referring the xml version and stuff at the top, there is an xml writer setting to turn that off.
var writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
using (var buffer = new StringWriter())
using (var writer = XmlWriter.Create(buffer, writerSettings))
{
cubbingmessagexml.Save(writer);
writer.Flush();
string result = buffer.ToString();
}
Skip the XDocument:
var cubbingmessagexml =
new XElement("MESSAGE", new XAttribute("ID", "CUB"),
new XElement("RECORD",
new XAttribute("STORENO", cubing.StoreID),
new XAttribute("TPNB", cubing.ProductCode),
new XAttribute("QUANTITY", cubing.Quantity),
new XAttribute("CUBINGTIME", cubing.CubingDateTime.ToString("yyyyMMddHHmmss")),
new XAttribute("SHELFFACING", cubing.ShelfFacing)
)
);
xml = cubbingmessagexml.ToString();
From MSDN:
Note that you only have to create XDocument objects if you require the specific functionality provided by the XDocument class. In many circumstances, you can work directly with XElement. Working directly with XElement is a simpler programming model.
and
As previously mentioned, the XElement class is the main class in the LINQ to XML programming interface. In many cases, your application will not require that you create a document. By using the XElement class, you can create an XML tree, add other XML trees to it, modify the XML tree, and save it.
Even with XDocument the declaration is not displayed.

How do you create standalone XML nodes in .NET?

How do you create a standalone XML node in .NET?
I have an XMLElement type that I'm trying to set a value to, but since the constructor for that class is protected, it won't let me do it.
This is what I'm currently doing:
XmlDocument xmldoc = new XmlDocument();
XmlElement foo = xmldoc.CreateElement("", "foo"); ;
XmlElement bar = xmldoc.CreateElement("", "bar"); ;
Is there a better way to do this?
If you use XElement from System.Xml.Linq instead of the old XmlElement from System.Xml it allows you to do that very easily:
new XElement("foo")
you can try this
public XElement ToXml()
{
XElement element = new XElement("Song",
new XElement("", "foo"),
new XElement("", "bar"));
return element;
}
I've done this in the past:
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
XmlElement fundsElement = doc.CreateElement("funds");
doc.AppendChild(fundsElement);
Are you on .NET 3.5 or later?
using System.Xml.Linq;
var element = new XElement("foo", "bar");
Console.WriteLine(element.ToString());
Output:
<foo>bar</foo>

Xml with two attributes in C#

I want to make xml element like this:
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>
Now I'm doing this in this way:
XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName ");
_xmlAttr = xmlDoc.CreateAttribute("Type");
_xmlAttr.Value = "FirstAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
_xmlAttr = xmlDoc.CreateAttribute("Name");
_xmlAttr.Value = "SecondAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value)
? SetTextLength(Name, ValueLength)
: string.Empty;
Value is input variable in method.
Is there possibility to make this in another way?
More efficiently?
Can I use xmlWriter? Now i'm using xmlDocument.
You can use Linq to XML.
Basically
XDocument doc = new XDocument();
doc.Add(
new XElement("ElementName", "Value",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute")));
will give this xml document
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>
How about tweaking your existing code:
XmlElement el = xmlDoc.CreateElement("ElementName");
el.SetAttribute("Type", "FirstAttribute");
el.SetAttribute("Name", "SecondAttribute");
el.InnerText = ...;
Additional thoughts:
XElement
XmlSerializer (from a class instance)
If you’re on .NET 3.5 (or later), you could use LINQ to XML. Make sure that the System.Xml.Linq assembly is referenced, and that you have a using directive for its eponymous namespace.
XDocument document = new XDocument(
new XElement("ElementName",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute"),
value));
If you subsequently want to write the XDocument to a target, you can use its Save method. For debugging, it’s useful to call its ToString method, which returns its XML representation as a string.
Edit: Replying to comment:
If you need to convert the XDocument created above into an XmlDocument instance, you may use code similar to the following:
XmlDocument xmlDocument = new XmlDocument();
using (XmlReader xmlReader = document.CreateReader())
xmlDocument.Load(xmlReader);
What about using LINQ to XML as in this article. That can be very elegant - it can all be done on one line.
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("element",
new XAttribute("attribute1", "val1"),
new XAttribute("attribute2", "val2"),
)
);

Deserialize XML into a C# object

How can I desearlize the below CatalogProduct tags into my CatalogProduct object using C#?
<?xml version="1.0" encoding="UTF-8"?>
<CatalogProducts>
<CatalogProduct Name="MyName1" Version="1.1.0"/>
<CatalogProduct Name="MyName2" Version="1.1.0"/>
</CatalogProducts>
Note i don't have a CatalogProducts object so want to skip that element when pulling back the into to deserialize
Thanks
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<CatalogProducts>" +
"<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" +
"<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" +
"</CatalogProducts>";
var document = XDocument.Parse(xml);
IEnumerable<CatalogProduct> catalogProducts =
from c in productsXml.Descendants("CatalogProduct")
select new CatalogProduct
{
Name = c.Attribute("Name").Value,
Version = c.Attribute("Version").Value
};
Just for your information, here's an example how to really serialize and deserialize an object:
private CatalogProduct Load()
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
using (var xmlReader = new XmlTextReader("CatalogProduct.xml"))
{
if (serializer.CanDeserialize(xmlReader))
{
return serializer.Deserialize(xmlReader) as CatalogProduct;
}
}
}
private void Save(CatalogProduct cp)
{
using (var fileStream = new FileStream("CatalogProduct.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
serializer.Serialize(fileStream, cp);
}
}
The canonical method would be to use the xsd.exe tool twice. First, to create a schema from your example XML as so:
xsd.exe file.xml will generate file.xsd.
Then:
xsd.exe /c file.xsd will generate file.cs.
File.cs will be the object(s) you can deserialize your XML from using any one of the techniques that you can easily find here, e.g. this.
Assuming your CatalogProduct object looks something like this:
public class CatalogProduct {
public string Name;
public string Version;
}
I think Linq to Xml will be the simplest and fastest way for you
var cps1 = new[] { new CatalogProduct { Name = "Name 1", Version = "Version 1" },
new CatalogProduct { Name = "Name 2", Version = "Version 2" } };
var xml = new XElement("CatalogProducts",
from c in cps1
select new XElement("CatalogProduct",
new XAttribute("Name", c.Name),
new XAttribute("Version", c.Version)));
// Use the following to deserialize you objects
var cps2 = xml.Elements("CatalogProduct").Select(x =>
new CatalogProduct {
Name = (string)x.Attribute("Name"),
Version = (string)x.Attribute("Version") }).ToArray();
Please note that .NET offers true object graph serialization which I have not shown
Without "CatalogProduct" object i think it's very difficult, maybe with the dynamic type of .net 4.0 it's possible, but i'm not sure.
The only way i know, is to utilize the XmlSerializer class with Deserialize method, but you need the object CatalogProduct.
I hope the following link is useful:
Link

Categories