I am having a problem with deserialization of an array which comes from the SOAP response. It returns null, but in response I can actually see a correct xml message. Maybe someone can see what's wrong in my code. Thanks in advance.
SOAP response:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns-wp="imcwp" xmlns:ns-hostax="imchostax" xmlns:ns-ilms="imcilms" xmlns:ns-qtms="imcqtms" xmlns:ns-tptms="imctptms">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns-wp:strTrailerRequest-TrailerResponse>
<ns-wp:Trailer>
<ns-wp:TrailerId>T001</ns-wp:TrailerId>
<ns-wp:TrailerType>Flat Extender</ns-wp:TrailerType>
</ns-wp:Trailer>
<ns-wp:Trailer>
<ns-wp:TrailerId>T002</ns-wp:TrailerId>
<ns-wp:TrailerType>Flat Extender</ns-wp:TrailerType>
</ns-wp:Trailer>
<ns-wp:Trailer>
<ns-wp:TrailerId>T003</ns-wp:TrailerId>
<ns-wp:TrailerType>Flat Extender</ns-wp:TrailerType>
</ns-wp:Trailer>
</ns-wp:strTrailerRequest-TrailerResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Response Model:
[XmlRoot(ElementName = "strTrailerRequest-TrailerResponse", Namespace = "imcwp")]
public class strTrailerRequestTrailerResponse
{
[XmlArray("strTrailerRequest-TrailerResponse", Namespace = "imcwp")]
[XmlArrayItem("Trailer", Namespace = "imcwp")]
public List<Trailer> Trailers { get; set; }
}
Parse Method:
private strTrailerRequestTrailerResponse ParseTrailerResponse(string response)
{
var soap = XDocument.Parse(response);
XNamespace ns = "imcwp";
var trailerResponseNode = soap.Descendants(ns + "strTrailerRequest-TrailerResponse").FirstOrDefault().ToString();
var result = Deserialize<strTrailerRequestTrailerResponse>(trailerResponseNode);
return result;
}
Why not just deserilize the whole object, in that case u dont need xDocument and querying:
var envelop = Deserialize<Envelope>(response);
foreach (var strTrailerRequestTrailerResponseTrailer in envelop.Body.strTrailerRequestTrailerResponse)
{
}
and yr Deserialize method:
public static T Deserialize<T>(string response)
{
var serializer = new XmlSerializer(typeof(T));
using(TextReader reader = new StringReader(response))
{
return (T)serializer.Deserialize(reader);
}
}
If you still want to go with yr way using XDocument, it's ok yr Deserialize method should the same as I defined. if you wont try:
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "imcwp")]
public partial class strTrailerRequestTrailerResponseTrailer
{
public string TrailerId { get; set; }
public string TrailerType { get; set; }
}
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "imcwp")]
[System.Xml.Serialization.XmlRootAttribute("strTrailerRequest-TrailerResponse", Namespace = "imcwp", IsNullable = false)]
public partial class strTrailerRequestTrailerResponse
{
[System.Xml.Serialization.XmlElementAttribute("Trailer")]
public strTrailerRequestTrailerResponseTrailer[] Trailer { get; set; }
}
For simple xml you can use xml linq. See code below :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace Certificate
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(xml);
XElement soap = doc.Root;
XNamespace ns = soap.GetNamespaceOfPrefix("ns-wp");
List<Trailer> trailers = doc.Descendants(ns + "Trailer").Select(x => new Trailer()
{
trailerId = (string)x.Element(ns + "TrailerId"),
trailerType = (string)x.Element(ns + "TrailerType")
}).ToList();
}
}
public class Trailer
{
public string trailerId { get; set; }
public string trailerType { get;set;}
}
}
Related
I got an XML response as:
<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="site.com/api" xmlns:xsi="site.org/2001/XMLSchema-instance" xsi:schemaLocation="site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd">
<credentials token="xxxxxx-xxxxxx-xxxxxx">
<site id="xxxxxx-xxxxxx-xxxxxx" contentUrl="sitename"/>
<user id="xxxxxx-xxxxxx-xxxxxx"/>
</credentials>
</tsResponse>
How can I parse this response to get the token value inside credentials?
By using LINQ to XML.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<tsResponse xmlns='site.com/api' xmlns:xsi='site.org/2001/XMLSchema-instance' xsi:schemaLocation='site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd'>
<credentials token='xxxxxx-xxxxxx-xxxxxx'>
<site id='xxxxxx-xxxxxx-xxxxxx' contentUrl='sitename'/>
<user id='xxxxxx-xxxxxx-xxxxxx'/>
</credentials>
</tsResponse>");
XNamespace ns1 = xdoc.Root.GetDefaultNamespace();
string token = xdoc.Descendants(ns1 + "credentials")
.FirstOrDefault()?.Attribute("token").Value;
Console.WriteLine("token = {0}", token);
}
Output
token = xxxxxx-xxxxxx-xxxxxx
I think that the simplest way is to use LINQ to XML's XDocument:
using System.Xml;
using System.Xml.Linq;
/* ... */
var xml = #"<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns=""site.com/api"" xmlns:xsi=""site.org/2001/XMLSchema-instance"" xsi:schemaLocation=""site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd"">
<credentials token=""xxxxxx-xxxxxx-xxxxxx"">
<site id=""xxxxxx-xxxxxx-xxxxxx"" contentUrl=""sitename""/>
<user id=""xxxxxx-xxxxxx-xxxxxx""/>
</credentials>
</tsResponse>";
var xmlns = XNamespace.Get("site.com/api");
var token = XDocument.Parse(xml)
.Element(xmlns + "tsResponse")?
.Element(xmlns + "credentials")?
.Attribute("token")?
.Value;
If you put the XML string that you get into the variable xmlToParse, you can do:
TsResponse result = _xmlParser.Deserialize<TsResponse>(xmlToParse);
Where _xmlParser is an instance of the class:
using System.Xml.Serialization;
namespace yourNameSpace
{
public class XmlParser
{
public T Deserialize<T>(string input) where T : class
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(input))
{
return (T)ser.Deserialize(sr);
}
}
}
}
You also need to model the whole XML object as a class in C# (XmlObjects.Credentials in my example) using the for example the page https://json2csharp.com/code-converters/xml-to-csharp which gives you:
// using System.Xml.Serialization;
// XmlSerializer serializer = new XmlSerializer(typeof(TsResponse));
// using (StringReader reader = new StringReader(xml))
// {
// var test = (TsResponse)serializer.Deserialize(reader);
// }
[XmlRoot(ElementName="site")]
public class Site {
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
[XmlAttribute(AttributeName="contentUrl")]
public string ContentUrl { get; set; }
}
[XmlRoot(ElementName="user")]
public class User {
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
[XmlRoot(ElementName="credentials")]
public class Credentials {
[XmlElement(ElementName="site")]
public Site Site { get; set; }
[XmlElement(ElementName="user")]
public User User { get; set; }
[XmlAttribute(AttributeName="token")]
public string Token { get; set; }
}
[XmlRoot(ElementName="tsResponse")]
public class TsResponse {
[XmlElement(ElementName="credentials")]
public Credentials Credentials { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="xsi")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName="schemaLocation")]
public string SchemaLocation { get; set; }
}
, then you can go with
result.Credentials.Token
Below is an example payload response from an integration I am currently working on. The response does not set a default namespace (xml2 variable in example) and the issue is that XmlSerializer does not assume the default namespace is "d". I have tried setting the default namespace in the XMLSerializer constructor but that doesn't work either. As well, I can't expect the "service" to update/fix their side. Is there some other settings I can pass that will correctly populate the class?
Thanks,
Chuck
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TestXmlNamespace
{
[XmlRoot(ElementName = "root", Namespace = "my_test_ns1")]
public class Test
{
public string name { get; set; }
public int age { get; set; }
[XmlElement(Namespace = "my_test_ns2")]
public int ageInMonths { get; set; }
public override bool Equals(object obj)
{
return obj is Test b && name == b.name && age == b.age && ageInMonths == b.ageInMonths;
}
public void Run(string str, string name)
{
XmlSerializer serializer = new XmlSerializer(typeof(Test));
using (StringReader rStream = new StringReader(str))
{
Test test = serializer.Deserialize(rStream) as Test;
Console.Out.WriteLine(test.Equals(this) ? $"{name} equals expected" : $"{name} does not equal expected");
}
}
}
class Program
{
const string xml1 = #"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<d:root xmlns:d=""my_test_ns1"" xmlns:v=""my_test_ns2"">
<d:name>Bill</d:name>
<d:age>32</d:age>
<v:ageInMonths>384</v:ageInMonths>
</d:root>
";
const string xml2 = #"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<d:root xmlns:d=""my_test_ns1"" xmlns:v=""my_test_ns2"">
<name>Bill</name>
<age>32</age>
<v:ageInMonths>384</v:ageInMonths>
</d:root>
";
static void Main(string[] args)
{
Test expected = new Test()
{
name = "Bill",
age = 32,
ageInMonths = 384
};
expected.Run(xml1, "xml1");
expected.Run(xml2, "xml2");
}
}
}
I found the solution and I am posting it for those in the future who may run across this problem and hopefully I will help them save some time.
Simply put, when an element does not have a namespace prefix XmlSerializer treats it has not part of a name space so specifying an empty name space in the element attribute handles this. See the updated example code below.
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TestXmlNamespace
{
public class CustomXmlTextReader : XmlTextReader
{
private readonly string DefaultNamespace = String.Empty;
public CustomXmlTextReader(StringReader reader, string defaultNamespace) : base(reader)
{
DefaultNamespace = defaultNamespace;
}
public override string NamespaceURI => String.IsNullOrEmpty(base.NamespaceURI) ? DefaultNamespace : base.NamespaceURI;
};
[XmlRoot(ElementName = "root", Namespace = "my_test_ns1")]
public class Test
{
[XmlElement("name", Namespace = "")] // Set namespace to empty string when no namespace prefix specified in xml
public string name { get; set; }
[XmlElement("age", Namespace = "")] // Set namespace to empty string when no namespace prefix specified in xml
public int age { get; set; }
[XmlElement(Namespace = "my_test_ns2")]
public int ageInMonths { get; set; }
public override bool Equals(object obj)
{
return obj is Test b && name == b.name && age == b.age && ageInMonths == b.ageInMonths;
}
public void Run(string str, string name)
{
using (StringReader rStream = new StringReader(str))
{
//using (XmlTextReader tr = new CustomXmlTextReader(rStream, "my_test_ns1"))
using (XmlTextReader tr = new XmlTextReader(rStream))
{
XmlSerializer serializer = new XmlSerializer(typeof(Test));
Test test = serializer.Deserialize(tr) as Test;
Console.Out.WriteLine(test.Equals(this) ? $"{name} equals expected" : $"{name} does not equal expected");
}
}
}
}
class Program
{
const string xml = #"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<d:root xmlns:d=""my_test_ns1"" xmlns:v=""my_test_ns2"">
<name>Bill</name>
<age>32</age>
<v:ageInMonths>384</v:ageInMonths>
</d:root>
";
static void Main(string[] args)
{
Test expected = new Test()
{
name = "Bill",
age = 32,
ageInMonths = 384
};
expected.Run(xml, "xml1");
}
}
}
I get from a webservice a XML like this:
<s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Get_PersonResponse
xmlns="http://tempuri.org/">
<Get_PersonResult
xmlns:a="http://schemas.datacontract.org/example"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:LASTNAME>DOE</a:LASTNAME>
<a:EMAIL/>
<a:FIRSTNAME>JONH</a:FIRSTNAME>
<a:NUM_CARD/>
<a:ID_PERSON>12345456</a:ID_PERSON>
<a:PHONE/>
</Get_PersonResult>
<RESP_COMMENT>"Person found"</RESP_COMMENT>
</Get_PersonResponse>
</s:Body>
</s:Envelope>
I want to check if RESP_COMMENT is empty. Then if is not empty get all the values (a:FIRSTNAME, a:LASTNAME, etc)
I got the a:FIRSTNAME on the fiddle but I am not sure if I have to do a bucle for every single value or is a better way to do it:
https://dotnetfiddle.net/cOsX6s
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(output);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("a:FIRSTNAME");
string lastname = string.Empty;
foreach (XmlNode node in nodeList)
{
firstname = node.InnerText;
Console.Write(firstname);
}
Try xml serialization :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication177
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
StringReader sReader = new StringReader(xml);
XmlReader xReader = XmlReader.Create(sReader);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(xReader);
}
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
}
public class Body
{
[XmlElement(ElementName = "Get_PersonResponse", Namespace = "http://tempuri.org/")]
public Get_PersonResponse Get_PersonResponse { get; set; }
}
public class Get_PersonResponse
{
[XmlElement(Namespace = "http://tempuri.org/")]
public string RESP_COMMENT { get; set; }
[XmlElement(ElementName = "Get_PersonResult", Namespace = "http://tempuri.org/")]
public Get_PersonResult Get_PersonResult { get; set; }
}
public class Get_PersonResult
{
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string LASTNAME { get;set;}
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string EMAIL { get; set; }
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string FIRSTNAME { get; set; }
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string NUM_CARD { get; set; }
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string ID_PERSON { get; set; }
[XmlElement(Namespace = "http://schemas.datacontract.org/example")]
public string PHONE { get; set; }
}
}
There should be a way to get this values using xpath. I have tried a few different things and it seems that the empty prefix on namespace xmlns="http://tempuri.org/" is causing problems, see the element Get_PersonResponse namespace attribute.
<Get_PersonResponse xmlns="http://tempuri.org/">
To overcome this problem we need to remove the namespace that is causing the problem before loading the xml.
using System;
using System.Xml;
public class Program
{
public static void Main()
{
string output = #"<s:Envelope
xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Body>
<Get_PersonResponse
xmlns=""http://tempuri.org/"">
<Get_PersonResult
xmlns:a=""http://schemas.datacontract.org/example""
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<a:LASTNAME>DOE</a:LASTNAME>
<a:EMAIL/>
<a:FIRSTNAME>JONH</a:FIRSTNAME>
<a:NUM_CARD/>
<a:ID_PERSON>12345456</a:ID_PERSON>
<a:PHONE/>
</Get_PersonResult>
<RESP_COMMENT>""Person found!""</RESP_COMMENT>
</Get_PersonResponse>
</s:Body>
</s:Envelope>";
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(output.Replace(#"xmlns=""http://tempuri.org/""", ""));
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmldoc.NameTable);
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("a", "http://schemas.datacontract.org/example");
var personResultNode = xmldoc.SelectSingleNode("//s:Envelope/s:Body/Get_PersonResponse/Get_PersonResult", nsmgr);
foreach (var nodes in personResultNode.ChildNodes)
{
var personAttribute = (XmlNode)nodes;
Console.WriteLine($"{personAttribute.LocalName}: {personAttribute.InnerText}");
}
Console.Read();
}
}
BTW: I have also tried to add an empty prefix for namespace xmlns="http://tempuri.org/" to the XmlNamespaceManager but that didn't help.
I need to make a api where in the request body there needs to be a CData object. All works exept that I cant figure out how to make my object serialze into a CData object. The project is written in the .net-framework.
I currently have the following code.
C#:
[XmlRoot(ElementName = "DATA")]
public class DATA
{
[XmlElement(ElementName = "ID")]
public int ID { get; set; }
[XmlElement(ElementName = "NAME")]
public string NAME{ get; set; }
}
[XmlRoot(ElementName = "NewDataSet")]
public class CDataSet
{
[XmlElement(ElementName = "DATA")]
public DATA data{ get; set; }
}
How the xml needs to look after:
<![CDATA[
<NewDataSet>
<DATA>
<ID>007</ID>
<NAME>John</NAME>
</DATA>
</NewDataSet>
]]>
I can make it working by serializing normally by making a request to this function:
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
Than manual adding the CData parts around it.
However my boss wants it make it work without manually adding the parts.
Please note I'm very new to C#.
Any step in the right direction will help. Thanks!
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
CDataSet data = new CDataSet()
{
data = new DATA() { ID = "007", NAME = "John" }
};
MemoryStream stream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(stream, settings);
XmlSerializer serializer = new XmlSerializer(typeof(CDataSet));
serializer.Serialize(writer, data);
writer.Flush();
writer.Close();
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
string xml = Encoding.UTF8.GetString(buffer);
string output = string.Format("<![CDATA[\n{0}\n]]>", xml);
}
}
[XmlRoot(ElementName = "DATA", Namespace = "")]
public class DATA
{
private int _ID { get; set; }
[XmlElement(ElementName = "ID")]
public string ID {
get { return _ID.ToString("D3");}
set{ _ID = int.Parse(value);}
}
[XmlElement(ElementName = "NAME")]
public string NAME { get; set; }
}
[XmlRoot(ElementName = "NewDataSet")]
public class CDataSet
{
[XmlElement(ElementName = "DATA")]
public DATA data { get; set; }
}
}
I have two class : Osoba, test
public class test
{
public string raz { get; set; }
public string dwa { get; set; }
}
public class Osoba
{
public test tehe { get; set; }
}
I also add namespaces to main root and seralize
Osoba ne = new Osoba();
test t1 = new praca2.test();
t1.dwa = "fgfg";
t1.raz = "dfdfdfdf";
ne.tehe = t1;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
ns.Add("d", "http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields");
ns.Add("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
XmlSerializer xsSubmit = new XmlSerializer(typeof(Osoba));
var xml = #"D:\dupa1.xml";
using (var stream = new FileStream(xml, FileMode.Create))
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
xsSubmit.Serialize(writer, ne,ns);
xml = stream.ToString(); // Your XML
}
}
I get
<?xml version="1.0" encoding="utf-8"?>
<Osoba xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution"xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls"xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields">
<tehe>
<raz>dfdfdfdf</raz>
<dwa>fgfg</dwa>
</tehe>
</Osoba>
I want add to node namespaces examle:
...
<pc:tehe>
<dfs:raz>dfdfdfdf</dfs:raz>
<dfs:dwa>fgfg</dfs:dwa>
</pc:tehe>
How I can do it?
I try add class atribute which set namespace
[XmlRoot("Node", Namespace="http://flibble")]
but it bad idea
You're almost there you just need to modify your classes slightly:
public class test
{
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution")]
public string raz { get; set; }
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution")]
public string dwa { get; set; }
}
public class Osoba
{
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2007/PartnerControls")]
public test tehe { get; set; }
}
Sample implementation copied mostly from yours:
class Program
{
static void Main(string[] args)
{
Osoba ne = new Osoba();
test t1 = new test();
t1.dwa = "fgfg";
t1.raz = "dfdfdfdf";
ne.tehe = t1;
XmlSerializer xsSubmit = new XmlSerializer(typeof(Osoba));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
ns.Add("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
var xml = #"D:\dupa1.xml";
using (var stream = new FileStream(xml, FileMode.Create))
{
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
{
xsSubmit.Serialize(writer, ne, ns);
}
}
}
}
You will get this XML:
<?xml version="1.0" encoding="utf-8"?>
<Osoba xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
<pc:tehe>
<dfs:raz>dfdfdfdf</dfs:raz>
<dfs:dwa>fgfg</dfs:dwa>
</pc:tehe>
</Osoba>
Hth...
Uisng xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication42
{
class Program
{
static void Main(string[] args)
{
string xmlHeader =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Osoba xmlns:dfs=\"http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\"" +
" xmlns:pc=\"http://schemas.microsoft.com/office/infopath/2007/PartnerControls\"" +
" xmlns:d=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\">" +
"</Osoba>";
XDocument doc = XDocument.Parse(xmlHeader);
XElement osoba = doc.Root;
XNamespace dfsNs = osoba.GetNamespaceOfPrefix("dfs");
XNamespace pcNs = osoba.GetNamespaceOfPrefix("pc");
osoba.Add(new XElement(pcNs + "tehe", new object[] {
new XElement(dfsNs + "raz", "dfdfdfdf"),
new XElement(dfsNs + "dwa", "fgfg")
}));
}
}
}
I think you are new at C#.I suggest you to study C# basics, design patterns and repository pattern.For your requirement you can use below codes
public class Tehe
{
public string Raz { get; set; }
public string Dwa { get; set; }
}
public class TeheRepository
{
private System.Xml.Linq.XDocument xmlDatas;
public TeheRepository(string filePath)
{
xmlDatas = XDocument.Load(filePath);
}
public IEnumerable<Tehe> FindAll()
{
return xmlDatas.Elements().Elements().Select(tehe =>
{
Tehe t = new Tehe();
t.Dwa = tehe.Elements().ElementAt(1).Value;
t.Raz = tehe.Elements().ElementAt(0).Value;
return t;
});
}
}