StringWriter.ToString() is breaking xml C# - c#

I have a class array that I'm going to pass to XML to send it later to SQL Server Stored Procedure.
The problem is that when I execute StringWriter it adds some scape caracters (=\) that appears in the final XML.
My code is the following:
public XmlDocument ToXML(object obj_to_xml)
{
string str_XML;
XmlDocument xml = new XmlDocument();
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(obj_to_xml.GetType());
serializer.Serialize(stringwriter, obj_to_xml);**
//at this point the format is correct, for example stringwriter contains:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfRegistroPrestamo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RegistroPrestamo>
<Id>1</Id>
<Cedula>8-834-789</Cedula>
<Nombre>Amarillos</Nombre>
<Apellido>Perez</Apellido>
</RegistroPrestamo>
<RegistroPrestamo>
<Id>0</Id>
<Cedula />
<Nombre />
<Apellido />
</RegistroPrestamo>
</ArrayOfRegistroPrestamo>
//the problem comes with this line
xml.LoadXml(stringwriter.ToString());
//final XML looks like this:
<?xml version=\"1.0\" encoding=\"utf-16\"?>
<ArrayOfRegistroPrestamo xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<RegistroPrestamo>
<Id>1</Id>
<Cedula>8-834-789</Cedula>
<Nombre>Amarillos</Nombre>
<Apellido>Perez</Apellido>
</RegistroPrestamo>
<RegistroPrestamo>
<Id>0</Id>
<Cedula />
<Nombre />
<Apellido />
</RegistroPrestamo>
</ArrayOfRegistroPrestamo>
return xml;
}
When SQL Server tries to parse the XML Code:
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "P_Save_Procedure";
cmd.Parameters.Add("#Registros", SqlDbType.Xml).Value = xml;
Stored Procedure Text
Create procedure [dbo].[P_Save_Procedure]
(#Registros as xml)
as
begin
select distinct 'Id' = x.v.value('Id[1]', 'Int')
from #Registros.nodes('/ArrayOfRegistroPrestamo/RegistroPrestamo') x(v)
end
I got the error:
Mens. 9413, Level 16, State 1, Line 4
XML parsing: line 1, character 37; It expected a string literal
If I call the SP manually with the correct version of the XML:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfRegistroPrestamo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RegistroPrestamo>
<Id>1</Id>
<Cedula>8-834-789</Cedula>
<Nombre>Amarillos</Nombre>
<Apellido>Perez</Apellido>
</RegistroPrestamo>
<RegistroPrestamo>
<Id>0</Id>
<Cedula />
<Nombre />
<Apellido />
</RegistroPrestamo>
</ArrayOfRegistroPrestamo>
The result is the expected.
Already have spend 2 days tryng to find a way to get the correct sintax for the XML and got nothing.

See this:
DoNotEscapeUriAttributes

Related

C# - How to serialize and derialize DataSet correctly?

I cannot deserialize the serialized dataset correctly if it has dates. The result is the dates are considered as a separate table instead of columns itself. It seems that it is not parsed correctly. How do I fix this?
Here are the variables under inspection after the serialization and deserialization. You can see that the deserializedDataSet.Tables has 2 counts where its original is just 1 count. I printed the table names and shows that the second table was date. Moreover, I can access the date column in the original data set but unable to access in the deserialized version.
Here is the serialized data of the dataset.
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<producttransactionsummary>
<id>74517</id>
<branchid>9999</branchid>
<date xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Year>2016</Year>
<Month>11</Month>
<Day>10</Day>
<Hour>18</Hour>
<Minute>25</Minute>
<Second>40</Second>
<Millisecond>0</Millisecond>
</date>
</producttransactionsummary>
<producttransactionsummary>
<id>74518</id>
<branchid>9999</branchid>
<date xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Year>2016</Year>
<Month>11</Month>
<Day>10</Day>
<Hour>18</Hour>
<Minute>25</Minute>
<Second>40</Second>
<Millisecond>0</Millisecond>
</NewDataSet>
Here is the deserialized dataset.
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<producttransactionsummary>
<id>74517</id>
<branchid>9999</branchid>
<date>
<Year>2016</Year>
<Month>11</Month>
<Day>10</Day>
<Hour>18</Hour>
<Minute>25</Minute>
<Second>40</Second>
<Millisecond>0</Millisecond>
</date>
</producttransactionsummary>
<producttransactionsummary>
<id>74518</id>
<branchid>9999</branchid>
<date>
<Year>2016</Year>
<Month>11</Month>
<Day>10</Day>
<Hour>18</Hour>
<Minute>25</Minute>
<Second>40</Second>
<Millisecond>0</Millisecond>
</date>
</producttransactionsummary>
</NewDataSet>
Here is my current code:
public static class Transport
{
public static MemoryStream Serialize(DataSet dataSet)
{
var memoryStream = new MemoryStream();
dataSet.WriteXml(memoryStream, XmlWriteMode.IgnoreSchema);
dataSet.WriteXml("input.xml");
memoryStream.Flush();
memoryStream.Position = 0;
return memoryStream;
}
public static DataSet Deserialize(MemoryStream stream)
{
var dataSet = new DataSet();
dataSet.ReadXml(stream);
dataSet.WriteXml("output.xml");
return dataSet;
}
}

Read element from SOAP message

I'm trying to read the APP_DATE element in this xml message. Tried using LINQ but unable to read MyResult
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<MyResponse xmlns="http://tempuri.org/">
<MyResult>
<APP_TYPE>I</APP_TYPE>
<APP_NO>152240</APP_NO>
<APP_DATE>10/03/2016</APP_DATE>
</MyResult>
</MyResponse>
</soap:Body>
</soap:Envelope>
Can't be sure because you didn't supply any example code but I assume you struggle because of the namespaces. So try this:
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
ns.AddNamespace("x", "http://tempuri.org/");
var result = doc.SelectSingleNode("//soap:Envelope/soap:Body/x:MyResponse/x:MyResult/x:APP_DATE", ns).InnerText;
For deeper understanding you can read this question
Using Linq it will be like this:
var result = XDocument.Load("data.xml").Root
.Descendants(XName.Get("APP_DATE", "http://tempuri.org/"))
.FirstOrDefault()?.Value;
See how in both examples I have to specify the namespaces of what I'm looking for

how to save the results of XPathSelectElements to xml in C#

I have an XML file and I wanna extract some elements using XPathSelectElements("..."). It works fine but I have no idea how to save the extracted data into a new XML file with a new outer wrap
Here's what I've got, XPathSelectElements works fine:
var doc = XDocument.Load("XXX.xml");
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
//code to save data to a new file...
My original xml file is like this:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order ID="1">aaa</Order>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
And I wanna save the result to a new xml file and with an extra wrap like this:
<?xml version="1.0" encoding="utf-8"?>
<newWrap>
<Orders>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
</newWrap>
Any help? Thanks a lot~
This is one possible way :
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
var root = new XElement("newWrap",
new XElement("Orders", nData)
);
var newDoc = new XDocument(root);
newDoc.Save("new_file.xml");
Dotnetfiddle Demo

Reading an innertext from an xml document

How do I get the innertext of the OverallResult element using SelectSingleNode?
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessResp xmlns="http://www.w3.org/2005/Atom">
<Result>
<OverallResult>Success</OverallResult>
var doc = new XmlDocument();
doc.LoadXml(xml);
var text = doc.SelectSingleNode("Example/Node/text()").InnerText; // or .Value
returns
"Some text here\r\n "
and text.Trim() returns
"Some text here"
Please go through the below link for XML related queries its very useful for begginers!
http://www.dotnetcurry.com/ShowArticle.aspx?ID=564
for your answer(i havnt tried it though try by changing like this in ur code)
doc.SelectSingleNode("soap/ProcessResp/ Result/OverallResult/text()").InnerText;

How to extract a part of xml code from an xml file using c# code

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<eRecon xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="eRecon.xsd">
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
<Detail>
<CarrierStatusDate>2010-01-11</CarrierStatusDate>
<ClaimNum>YDF02892 C</ClaimNum>
<InvoiceNum>0108013775</InvoiceNum>
<LineItemNum>001</LineItemNum>
<NABP>10600211</NABP>
<RxNumber>4695045</RxNumber>
<RxDate>2008-07-21</RxDate>
<CheckNum />
<PaymentStatus>PENDING</PaymentStatus>
<RejectDescription />
<InvoiceChargeAmount>152.15</InvoiceChargeAmount>
<InvoicePaidAmount>131.00</InvoicePaidAmount>
</Detail>
</eRecon>
How can I extract the portion
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
from the above xml file.
I need the c# code to extract a part of xml tag from an xml file.
If the file isn't too big (smaller than a few MB), you can load it into an XmlDocument:
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\yourfile.xml");
and then you can parse for the <Header> element using an XPath expression:
XmlNode headerNode = doc.SelectSingleNode("/eRecon/Header");
if(headerNode != null)
{
string headerNodeXml = headerNode.OuterXml;
}
You can use XPath like in this tutorial:
http://www.codeproject.com/KB/cpp/myXPath.aspx
Use Linq-to-xml:
XDocument xmlDoc = XDocument.Load(#"c:\sample.xml");
var header = xmlDoc.Descendants("Header").FirstOrDefault();
Linq version
string fileName=#"d:\xml.xml";
var descendants = from i in XDocument.Load(fileName).Descendants("Header")
select i;

Categories

Resources