Quantcast
Channel: XML, System.Xml, MSXML and XmlLite forum
Viewing all 935 articles
Browse latest View live

Remove XML that does not validate against XSD.

$
0
0
<!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-ansi-language:EN-GB;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} -->

Hi,

I have two Streams, one containing an XML file and the other an XSD.

 

I currently upload the XML stream to an SQL Server database using SQLXMLBulkLoad. 

 

The problem I have is that if one element\attribute fails during the upload then nothing is uploaded.  Therefore using the XSD, I would like to strip out any invalid “rows” prior to the upload.

 

My data takes the following structure, where Column1 and Column2 are integers.

 

<TableName>
<Row>
<Column1>1</Column1>
<Column2>2</Column2>
</Row>
<Row>
<Column1>1</Column1>
<Column2>2</Column2>
</Row>
<Row>
<Column1>1</Column1>
<Column2>B</Column2>
</Row>
</TableName>

 

In the above example, Column2 in the 3rd Row is invalid.  Therefore I would like to remove it from the XML.

 

Is this possible in C#?  My ideal solution would not load the whole stream in to Memory.

 

Thanks,

Ben.


giuntini maurizio

Rename node, XSLT 1.0

$
0
0

Hello,

I have an XML like this:

<Temp_Node_A>data</Temp_Node_A>
<Temp_Node_B>data</Temp_Node_B>
... etc ...

I want it converted to

<Node_A>data</Node_A>
<Node_B>data</Node_B>
... etc ...

That is, I want to remove "Temp_" from every node that starts with Temp_ (or /Temp)

With XSLT 1.0, is it possible? If so, can you give an example?

Regards
Peter

MSXML6.dll in Windows8 breaks legacy apps.

$
0
0

Our application written in VB6 uses DOMDocument40 which is an object exposed in MSXML6.dll in older versions of Windows.

The MSXML6.dll with Windows8 is different and does not expose DOMDocument40, causing our application to break on customers who upgrade to Windows8.

Is there any solution except we change our app to use DOMDocument60 and supply an update to all our customers? 

Console App Does not return XML Data when Calling an HTTP Webservice

$
0
0

Hi,

I've written a C# console application to call a RESTful HTTP web service per below:

class Program
    {
        static void Main(string[] args)
        {
        string URL = "https://sapiqa.overstock.com/api";
        string APIMethod = "GetOrders2";
        string MerchantKey = "OurMerchKey";
        string AuthenticationKey = "OurAuthKey";
        string GetOrders2Response;
        WebRequest wrq = WebRequest.Create("https://sapiqa.overstock.com/api?" + APIMethod + "?MerchantKey=" + MerchantKey + "?AuthenticationKey=" + AuthenticationKey);
        wrq.Method = "POST";
        // Create POST data and convert it to a byte array. Strip out unnecessary text.
        byte[] byteArray = Encoding.UTF8.GetBytes(URL.Replace(APIMethod, ""));
        // Set the ContentType property of the WebRequest.
        wrq.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        wrq.ContentLength = byteArray.Length;

        Stream dataStream = wrq.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = wrq.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        GetOrders2Response = responseFromServer;
        Console.WriteLine(responseFromServer);

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();
        Console.ReadKey();
        }
    }

The solution builds without errors.  When I F5 to debug, the console window doesn't stay open and I see no confirmation that the web service was called or the response that was recieved.

How do I keep the console open?  What must be done to write the XML response to SQL Server?  Ideally, I want to use this as a script component in SSIS but want to start with the basicss first.

Thanks for your help and guidance.

xml xsd

$
0
0

WHAT IS THE MEANING OF :

<xs:pattern value="[1-9]{1}[0-9]{3}[//][0-9]{2}"/>

Controling XML Serialization

$
0
0

Hi to all,

XML Example into msdn documentation,

publicclass Group{ [XmlArrayItem(Type = typeof(Employee)), XmlArrayItem(Type = typeof(Manager))]public Employee[] Employees; }publicclass Employee{publicstring Name; }publicclass Manager:Employee{publicint Level; }

This serialize into XML :

<Group><Employees><Employee><Name>Haley</Name></Employee><Employee xsi:type = "Manager"><Name>Ann</Name><Level>3</Level><Employee></Employees ></Group>

How add attribute serialization for serialize in this XML ?

<Group><Employees><Employee><Name>Haley</Name></Employee><Employee>

<Manager><Name>Ann</Name><Level>3</Level>

</Manager><Employee></Employees ></Group>

ok is need to add XMLInclude of type manger but for requeriments of mi client i need to "convert manager type in

data element"

Thanks , to all

Jordi


Jordi Burgas


Xmlreader read end tag problem

$
0
0

Hi guys:

   I am a xml file like follow:

 

<?xmlversion="1.0"encoding="utf-8"?><Response><Roomname="ro1"><Chairname="ch1">ABCD1</Chair></Room><Roomname="ro2"><Chairname="ch2">ABCD2</Chair></Room><Roomname="ro3"><Chairname="ch3">ABCD3</Chair></Room><Roomname="ro4"><Chairname="ch4">ABCD4</Chair></Room></Response>

 

and I read it:

 

while (xmlReader.Read())
   {switch (xmlReader.Name)
    {case"Room":if(xmlReader.IsStartElement())
      {
       Console.WriteLine("start room");
      }else
      {
       Console.WriteLine("end room");
      }break;case"Chair":if (xmlReader.IsStartElement())
      {
       Console.WriteLine("start chair");
      }else
      {
       Console.WriteLine("end chair");
      }break;
    }
   }

 

it works fine, and print out

start room
start chair
end chair
end room
start room
start chair
end chair
end room
start room
start chair
end chair
end room
start room
start chair
end chair
end room

 

 

that's what I excepted!

but if I change the code like:

 

while (xmlReader.Read())
   {switch (xmlReader.Name)
    {case"Room":if(xmlReader.IsStartElement())
      {
       Console.WriteLine("start room");
      }else
      {
       Console.WriteLine("end room");
      }break;case"Chair":if (xmlReader.IsStartElement())
      {
       Console.WriteLine("start chair");
      }else
      {
       Console.WriteLine("end chair");
      }var chairContent = xmlReader.ReadElementContentAsString();
      Console.WriteLine("chair content is:"+chairContent);break;
    }
   }

 

then the end tag of chair can not be reached! out put like:

start room
start chair
chair content is:ABCD1
end room
start room
start chair
chair content is:ABCD2
start room
start chair
chair content is:ABCD3
end room
start room
start chair
chair content is:ABCD4
end room

if I change the xml, delete the new line between chair and room, like

 

<?xmlversion="1.0"encoding="utf-8"?><Response><Roomname="ro1"><Chairname="ch1">ABCD1</Chair></Room><Roomname="ro2"><Chairname="ch2">ABCD2</Chair></Room><Roomname="ro3"><Chairname="ch3">ABCD3</Chair></Room><Roomname="ro4"><Chairname="ch4">ABCD4</Chair></Room></Response>

 

both the end chair and end room can not be reached, print like follow:

start room
start chair
chair content is:ABCD1
start room
start chair
chair content is:ABCD2
start room
start chair
chair content is:ABCD3
start room
start chair
chair content is:ABCD4


zbo

XML to XML using XSLT

$
0
0

Hi

 I have a XML script which includes inline schema values. I need to convert into to proper XL data. 

Available Code,

<?xml version="1.0" encoding="UTF-16"?>

-<DataSet>


-<xs:schema xmlns:app2="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:app1="http://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:sql:SqlDataSet" xmlns:mstns="urn:schemas-microsoft-com:sql:SqlDataSet" targetNamespace="urn:schemas-microsoft-com:sql:SqlDataSet" id="SqlDataSet"><xs:import namespace="urn:schemas-microsoft-com:sql:SqlRowSet1"/><xs:import namespace="http://schemas.microsoft.com/sqlserver/2004/sqltypes"/>


-<xs:element msdata:UseCurrentLocale="true" msdata:IsDataSet="true" name="SqlDataSet">


-<xs:complexType>


-<xs:choice maxOccurs="unbounded" minOccurs="0"><xs:element ref="app2:row"/></xs:choice></xs:complexType></xs:element></xs:schema>


-<xs:schema xmlns:app2="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:app1="http://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/sqlserver/2004/sqltypes" xmlns:mstns="urn:schemas-microsoft-com:sql:SqlDataSet" targetNamespace="http://schemas.microsoft.com/sqlserver/2004/sqltypes"><xs:import namespace="urn:schemas-microsoft-com:sql:SqlRowSet1"/><xs:import namespace="urn:schemas-microsoft-com:sql:SqlDataSet"/>


-<xs:simpleType name="int"><xs:restriction base="xs:int"/></xs:simpleType>


-<xs:simpleType name="varchar"><xs:restriction base="xs:string"/></xs:simpleType>


-<xs:simpleType name="numeric"><xs:restriction base="xs:decimal"/></xs:simpleType></xs:schema>


-<xs:schema xmlns:app2="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:app1="http://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:mstns="urn:schemas-microsoft-com:sql:SqlDataSet" targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet1"><xs:import namespace="http://schemas.microsoft.com/sqlserver/2004/sqltypes"/><xs:import namespace="urn:schemas-microsoft-com:sql:SqlDataSet"/>


-<xs:element name="row">


-<xs:complexType>


-<xs:sequence><xs:element name="PlayerID" type="app1:int"/>


-<xs:element name="PlayerName" minOccurs="0">


-<xs:simpleType>


-<xs:restriction base="app1:varchar"><xs:maxLength value="15"/></xs:restriction></xs:simpleType></xs:element>


-<xs:element name="BelongsTo" minOccurs="0">


-<xs:simpleType>


-<xs:restriction base="app1:varchar"><xs:maxLength value="15"/></xs:restriction></xs:simpleType></xs:element><xs:element name="MatchPlayed" minOccurs="0" type="app1:int"/><xs:element name="RunsMade" minOccurs="0" type="app1:int"/><xs:element name="WicketsTaken" minOccurs="0" type="app1:int"/>


-<xs:element name="FeePerMatch" minOccurs="0" msdata:DataType="System.Data.SqlTypes.SqlDecimal">


-<xs:simpleType><xs:restriction base="app1:numeric"/></xs:simpleType></xs:element></xs:sequence></xs:complexType></xs:element></xs:schema>


-<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">


-<SqlDataSet xmlns="urn:schemas-microsoft-com:sql:SqlDataSet">


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row1" msdata:rowOrder="0"><PlayerID>1</PlayerID><PlayerName>A. Won</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>440</RunsMade><WicketsTaken>10</WicketsTaken><FeePerMatch>1000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row2" msdata:rowOrder="1"><PlayerID>2</PlayerID><PlayerName>A. Cricket</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>17</WicketsTaken><FeePerMatch>400000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row3" msdata:rowOrder="2"><PlayerID>3</PlayerID><PlayerName>B. Dhanman</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>650</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>3600000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row4" msdata:rowOrder="3"><PlayerID>4</PlayerID><PlayerName>C. Barsat</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>950</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>5000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row5" msdata:rowOrder="4"><PlayerID>5</PlayerID><PlayerName>A. Mirza</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>2</MatchPlayed><RunsMade>3</RunsMade><WicketsTaken>38</WicketsTaken><FeePerMatch>3600000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row6" msdata:rowOrder="5"><PlayerID>6</PlayerID><PlayerName>M. Karol</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>15</MatchPlayed><RunsMade>44</RunsMade><WicketsTaken>4</WicketsTaken><FeePerMatch>2000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row7" msdata:rowOrder="6"><PlayerID>7</PlayerID><PlayerName>Z. Hamsa</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>3</MatchPlayed><RunsMade>580</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>400.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row8" msdata:rowOrder="7"><PlayerID>8</PlayerID><PlayerName>K. Loly</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>6</MatchPlayed><RunsMade>500</RunsMade><WicketsTaken>12</WicketsTaken><FeePerMatch>800000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row9" msdata:rowOrder="8"><PlayerID>9</PlayerID><PlayerName>S. Summer</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>87</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>8</WicketsTaken><FeePerMatch>1230000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row10" msdata:rowOrder="9"><PlayerID>10</PlayerID><PlayerName>J.June</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>12</MatchPlayed><RunsMade>510</RunsMade><WicketsTaken>9</WicketsTaken><FeePerMatch>4988000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row11" msdata:rowOrder="10"><PlayerID>11</PlayerID><PlayerName>A.Namaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>1</MatchPlayed><RunsMade>4</RunsMade><WicketsTaken>180</WicketsTaken><FeePerMatch>999999.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row12" msdata:rowOrder="11"><PlayerID>12</PlayerID><PlayerName>Z. Samaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>2</MatchPlayed><RunsMade>6</RunsMade><WicketsTaken>147</WicketsTaken><FeePerMatch>888888.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row13" msdata:rowOrder="12"><PlayerID>13</PlayerID><PlayerName>MS. Kaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>40</MatchPlayed><RunsMade>66</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>1234.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row14" msdata:rowOrder="13"><PlayerID>14</PlayerID><PlayerName>S. Boon</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>170</MatchPlayed><RunsMade>888</RunsMade><WicketsTaken>10</WicketsTaken><FeePerMatch>890.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row15" msdata:rowOrder="14"><PlayerID>15</PlayerID><PlayerName>DC. Shane</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>28</MatchPlayed><RunsMade>39</RunsMade><WicketsTaken>338</WicketsTaken><FeePerMatch>4444499.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row16" msdata:rowOrder="15"><PlayerID>16</PlayerID><PlayerName>S. Noami</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>165</MatchPlayed><RunsMade>484</RunsMade><WicketsTaken>45</WicketsTaken><FeePerMatch>5678.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row17" msdata:rowOrder="16"><PlayerID>17</PlayerID><PlayerName>Z. Biswas</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>73</MatchPlayed><RunsMade>51</RunsMade><WicketsTaken>50</WicketsTaken><FeePerMatch>22222.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row18" msdata:rowOrder="17"><PlayerID>18</PlayerID><PlayerName>K. Dolly</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>65</MatchPlayed><RunsMade>59</RunsMade><WicketsTaken>1</WicketsTaken><FeePerMatch>99999.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row19" msdata:rowOrder="18"><PlayerID>19</PlayerID><PlayerName>S. Winter</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>7</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>8</WicketsTaken><FeePerMatch>12.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row20" msdata:rowOrder="19"><PlayerID>20</PlayerID><PlayerName>J.August</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>9</MatchPlayed><RunsMade>99</RunsMade><WicketsTaken>98</WicketsTaken><FeePerMatch>890.00</FeePerMatch></row></SqlDataSet></diffgr:diffgram></DataSet>

I need to get like below for that what XSLT, i should use?

-<SqlDataSet xmlns="urn:schemas-microsoft-com:sql:SqlDataSet">


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row1" msdata:rowOrder="0"><PlayerID>1</PlayerID><PlayerName>A. Won</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>440</RunsMade><WicketsTaken>10</WicketsTaken><FeePerMatch>1000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row2" msdata:rowOrder="1"><PlayerID>2</PlayerID><PlayerName>A. Cricket</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>17</WicketsTaken><FeePerMatch>400000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row3" msdata:rowOrder="2"><PlayerID>3</PlayerID><PlayerName>B. Dhanman</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>650</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>3600000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row4" msdata:rowOrder="3"><PlayerID>4</PlayerID><PlayerName>C. Barsat</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>10</MatchPlayed><RunsMade>950</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>5000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row5" msdata:rowOrder="4"><PlayerID>5</PlayerID><PlayerName>A. Mirza</PlayerName><BelongsTo>India</BelongsTo><MatchPlayed>2</MatchPlayed><RunsMade>3</RunsMade><WicketsTaken>38</WicketsTaken><FeePerMatch>3600000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row6" msdata:rowOrder="5"><PlayerID>6</PlayerID><PlayerName>M. Karol</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>15</MatchPlayed><RunsMade>44</RunsMade><WicketsTaken>4</WicketsTaken><FeePerMatch>2000000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row7" msdata:rowOrder="6"><PlayerID>7</PlayerID><PlayerName>Z. Hamsa</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>3</MatchPlayed><RunsMade>580</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>400.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row8" msdata:rowOrder="7"><PlayerID>8</PlayerID><PlayerName>K. Loly</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>6</MatchPlayed><RunsMade>500</RunsMade><WicketsTaken>12</WicketsTaken><FeePerMatch>800000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row9" msdata:rowOrder="8"><PlayerID>9</PlayerID><PlayerName>S. Summer</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>87</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>8</WicketsTaken><FeePerMatch>1230000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row10" msdata:rowOrder="9"><PlayerID>10</PlayerID><PlayerName>J.June</PlayerName><BelongsTo>US</BelongsTo><MatchPlayed>12</MatchPlayed><RunsMade>510</RunsMade><WicketsTaken>9</WicketsTaken><FeePerMatch>4988000.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row11" msdata:rowOrder="10"><PlayerID>11</PlayerID><PlayerName>A.Namaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>1</MatchPlayed><RunsMade>4</RunsMade><WicketsTaken>180</WicketsTaken><FeePerMatch>999999.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row12" msdata:rowOrder="11"><PlayerID>12</PlayerID><PlayerName>Z. Samaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>2</MatchPlayed><RunsMade>6</RunsMade><WicketsTaken>147</WicketsTaken><FeePerMatch>888888.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row13" msdata:rowOrder="12"><PlayerID>13</PlayerID><PlayerName>MS. Kaki</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>40</MatchPlayed><RunsMade>66</RunsMade><WicketsTaken>0</WicketsTaken><FeePerMatch>1234.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row14" msdata:rowOrder="13"><PlayerID>14</PlayerID><PlayerName>S. Boon</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>170</MatchPlayed><RunsMade>888</RunsMade><WicketsTaken>10</WicketsTaken><FeePerMatch>890.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row15" msdata:rowOrder="14"><PlayerID>15</PlayerID><PlayerName>DC. Shane</PlayerName><BelongsTo>Australia</BelongsTo><MatchPlayed>28</MatchPlayed><RunsMade>39</RunsMade><WicketsTaken>338</WicketsTaken><FeePerMatch>4444499.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row16" msdata:rowOrder="15"><PlayerID>16</PlayerID><PlayerName>S. Noami</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>165</MatchPlayed><RunsMade>484</RunsMade><WicketsTaken>45</WicketsTaken><FeePerMatch>5678.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row17" msdata:rowOrder="16"><PlayerID>17</PlayerID><PlayerName>Z. Biswas</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>73</MatchPlayed><RunsMade>51</RunsMade><WicketsTaken>50</WicketsTaken><FeePerMatch>22222.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row18" msdata:rowOrder="17"><PlayerID>18</PlayerID><PlayerName>K. Dolly</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>65</MatchPlayed><RunsMade>59</RunsMade><WicketsTaken>1</WicketsTaken><FeePerMatch>99999.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row19" msdata:rowOrder="18"><PlayerID>19</PlayerID><PlayerName>S. Winter</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>7</MatchPlayed><RunsMade>50</RunsMade><WicketsTaken>8</WicketsTaken><FeePerMatch>12.00</FeePerMatch></row>


-<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" diffgr:id="row20" msdata:rowOrder="19"><PlayerID>20</PlayerID><PlayerName>J.August</PlayerName><BelongsTo>Singapore</BelongsTo><MatchPlayed>9</MatchPlayed><RunsMade>99</RunsMade><WicketsTaken>98</WicketsTaken><FeePerMatch>890.00</FeePerMatch></row></SqlDataSet>

Thanks

 

How to create XmlDocument object based on XSD at runtime in c#

$
0
0
Hi,

I have multiple XML Schema's basedon which I would like to create XmlDocument object. Unlike creating a XmlDataDocument or DataSet from schema, there seems to be no way to create XmlDocument from schema runtime in c#. We don't want to use XSD.exe as it makes classes which is kind of earliy binding.

Any ideas how to create XMLDocument objects based on XSD schema files in runtime?

Thanks.

Missing prefix "saml:" when Using "Microsoft.IdentityModel.Tokens.Saml2" to make SAML V2.0

$
0
0

why can SAML2 produce a SAML where it use the prefix "SAML:" Like in this exemple:

   <?xml version="1.0" encoding="utf-8"?>
   <saml:Assertion ID="_51bc8a37-0b6d-4e13-81e9-e1778a9b4dd3" IssueInstant="2012-10-10T19:32:07.526Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <saml:Issuer>someidentifier</Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
     <ds:SignedInfo>
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <ds:Reference URI="#_51bc8a37-0b6d-4e13-81e9-e1778a9b4dd3">
       <ds:Transforms>
        <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
       </ds:Transforms>
       <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
       <ds:DigestValue>N3UrIhpT+EXn+CeMiaq98v4n6vWw=</ds:DigestValue>
      </ds:Reference>
     </ds:SignedInfo>
<ds:SignatureValue>ACDCBN55g2FTo82jWjfN67BQB7XyC1UxUIqr6iAGfu85O2P7WCkqDxPhsaveOOVkNgz1r4KkSEAdFdv5sh4xCumooUVAiQXYFMgGz6QSNjdsxUurrmetyrDLQOtU2phuAykY9bF4kNYuYBgvDygCq6gbv8DR+M83WbKFMHRy7nYkrHZg0DJw56aiHnZvZQr/VyIsSvxGU7ra9ED4Tbe26oWte8ysb71yAZKqcEzzFKZU1BmMoApwJU3DLVqHo5r335ayPYxcsvm3LJ3vIDx+ql3tEKFSlt2OLBYSMlhCGYbyxMwAmzWzgv53zx1DiXrBxsSFzrbqk7y4PNx2eE0NciA==</ds:SignatureValue>
     <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
      <o:SecurityTokenReference xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
       <o:KeyIdentifier ValueType="kdkT3iOnlm4C8J3oa4/KPHOyqngc=</o:KeyIdentifier">http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1">kdkT3iOnlm4C8J3oa4/KPHOyqngc=</o:KeyIdentifier>
      </o:SecurityTokenReference>
     </KeyInfo>
    </ds:Signature>
    <saml:Subject>
     <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">12345</saml:NameID>
     <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
     </saml:SubjectConfirmation>
    </saml:Subject>
    <saml:Conditions NotBefore="2012-10-10T19:31:37.526Z" NotOnOrAfter="2012-10-10T19:32:37.526Z">
    </saml:Conditions>
    <saml:AttributeStatement>
     <saml:Attribute Name="userud">
      <saml:AttributeValue>999999</saml:AttributeValue>
     </saml:Attribute>
    </saml:AttributeStatement>
   </saml:Assertion>

 

 

but all I can produce is (where's the "SAML" prefix?):


   <?xml version="1.0" encoding="utf-8"?>
   <Assertion ID="_51bc8a37-0b6d-4e13-81e9-e1778a9b4dd3" IssueInstant="2012-10-10T19:32:07.526Z" Version="2.0" xmlns="urn:oasis:names:tc:2.0:assertion">
    <Issuer>someidentifier</Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
     <ds:SignedInfo>
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <ds:Reference URI="#_51bc8a37-0b6d-4e13-81e9-e1778a9b4dd3">
       <ds:Transforms>
        <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
       </ds:Transforms>
       <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
       <ds:DigestValue>N3UrIhpT+EXn+CeMiaq98v4n6vWw=</ds:DigestValue>
      </ds:Reference>
     </ds:SignedInfo>
     <ds:SignatureValue>ACDCBN55g2FTo82jWjfN67BQB7XyC1UxUIqr6iAGfu85O2P7WCkqDxPhsaveOOVkNgz1r4KkSEAdFdv5sh4xCumooUVAiQXYFMgGz6QSNjdsxUurrmetyrDLQOtU2phuAykY9bF4kNYuYBgvDygCq6gbv8DR+M83WbKFMHRy7nYkrHZg0DJw56aiHnZvZQr/VyIsSvxGU7ra9ED4Tbe26oWte8ysb71yAZKqcEzzFKZU1BmMoApwJU3DLVqHo5r335ayPYxcsvm3LJ3vIDx+ql3tEKFSlt2OLBYSMlhCGYbyxMwAmzWzgv53zx1DiXrBxsSFzrbqk7y4PNx2eE0NciA==</ds:SignatureValue>
     <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
      <o:SecurityTokenReference xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
       <o:KeyIdentifier ValueType="kdkT3iOnlm4C8J3o4/KPHOyqngc=</o:KeyIdentifier">http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1">kdkT3iOnlm4C8J3o4/KPHOyqngc=</o:KeyIdentifier>
      </o:SecurityTokenReference>
     </KeyInfo>
    </ds:Signature>
    <Subject>
     <NameID Format="urn:oasis:names:tc:2.0:attrname-format:unspecified">12345</NameID>
     <SubjectConfirmation Method="urn:oasis:names:tc:2.0:cm:bearer">
     </SubjectConfirmation>
    </Subject>
    <Conditions NotBefore="2012-10-10T19:31:37.526Z" NotOnOrAfter="2012-10-10T19:32:37.526Z">
    </Conditions>
    <AttributeStatement>
     <Attribute Name="userud">
      <AttributeValue>999999</AttributeValue>
     </Attribute>
    </AttributeStatement>
   </Assertion>

 

 

 

 

 

 

 

 

 

Here is my code:


 
   Saml2NameIdentifier assertionNameIdentifier = new Saml2NameIdentifier("someidentifier");
   Saml2Assertion assertion = new Saml2Assertion(assertionNameIdentifier);
   assertion.Id = new Saml2Id(SamlAssertionID);
   assertion.IssueInstant = dtIssueInstant;
   assertion.Conditions = new Saml2Conditions();
   assertion.Conditions.NotBefore = dtNotBefore;
   assertion.Conditions.NotOnOrAfter = dtNotOnOrAfter;
   //
   // Create some SAML subject.
   assertion.Subject = new Saml2Subject();
   assertion.Subject.NameId = new Saml2NameIdentifier("12345");
   assertion.Subject.NameId.Format = new Uri("urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");
   
   //
   // Now create the SAML statement containing one attribute and one subject.
   Saml2AttributeStatement samlAttributeStatement = new Saml2AttributeStatement();
   
   //
   // Create one SAML attribute with few values.
   Saml2Attribute attr = null;
   
   attr = new Saml2Attribute("userid");
   attr.FriendlyName = "userid";
   attr.Values.Add("999999");
   samlAttributeStatement.Attributes.Add(attr);
   
   // Append the statement to the SAML assertion.
   assertion.Statements.Add(samlAttributeStatement);
   
   
   /**************************************************************
   * END createSamlAssertion()
   **************************************************************/
   
   //
   // Signing credentials are consisted
   // of private key in the certificate (see above),
   // the signature algorithm, security algortihm and key identifier.
   assertion.SigningCredentials =
   new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha1Signature,
                   SecurityAlgorithms.Sha1Digest,
                   new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(SigningCert)));
   
   
   
   // Finally create the SamlSecurityToken from the assertion
   Saml2SecurityToken samlToken = new Saml2SecurityToken(assertion);
   
   
   var tokenhandler = new Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler();
   
   var settings = new XmlWriterSettings();
   settings.Indent = false;
   settings.Encoding = Encoding.UTF8;
   
   using (var xWriter = XmlWriter.Create(@"c:\saml2.xml", settings))
   {
      
       Debug.WriteLine(xWriter.LookupPrefix("urn:oasis:names:tc:SAML:2.0:assertion"));
       tokenhandler.WriteToken(xWriter, samlToken);
       xWriter.Flush();
       xWriter.Close();
   }

 

XmlDocument.Save() - Automatic indenting?

$
0
0

Hi

I've added a new Xml-node to my XmlDocument:

XmlDocument xml = newXmlDocument();
xml.Load(
"books.xml");
XmlNode fragment = xml.CreateDocumentFragment();
fragment.InnerXml =
"<Book><Title>MyBook</Title></Book>";
xml.DocumentElement.AppendChild(fragment);
xml.Save(
"books.xml");

The problem is that the added node is not correctly indented.
I want the output to be:

<Book>
  <Title>
    MyBook
  </Title>
</Book>

How do I do this?

Kind Regards

Element is not declared validation error post upgrading from .Net v4.5 to .Net v4.5.2

$
0
0

I understand that there are already many existing threads for the 'element not found' error for XML validation but I'm posting this as my problem is slightly different.

My code was running fine until it was on .Net v4.5. After upgrading the framework to v4.6.1, I started getting this error for each XML element in my xml file. Upon downgrading I found that the error started occurring from .Net framework v4.5.2 onwards. Below is my code:

XML - Book.xml

<?xml version="1.0" ?><!DOCTYPE book SYSTEM "Book.dtd"><book><title>The Lord of the Rings</title><author>J.R.R. Tolkien</author><isbn>1572810556</isbn></book>

DTD - Book.dtd

<!ELEMENT book (title, author, isbn)><!ELEMENT title (#PCDATA)><!ELEMENT author (#PCDATA)><!ELEMENT isbn (#PCDATA)>

C# Functions

public static void ReadXMLwithDTD()
{
    // Set the validation settings.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.DTD;
    settings.DtdProcessing = DtdProcessing.Parse;
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    settings.IgnoreWhitespace = true;

    // Create the XmlReader object.
    XmlReader reader = XmlReader.Create("Book.xml", settings);

    // Parse the file.
    while (reader.Read())
    {
        Console.WriteLine("{0}, {1}: {2} ", reader.NodeType, reader.Name, reader.Value);
    }
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
        Console.WriteLine("Warning: Matching schema not found.  No validation occurred." + e.Message);
    else // Error
        Console.WriteLine("Validation error: " + e.Message);
}

When the code is executed the callback throws validation errors (element not found) for all four XML elements - book, title, author and isbn.

I also found that DTD is not read. I introduced errors in the dtd file, even renamed the file, there was no change. Next, I reverted the errors and switched the framework back to 4.5, the code worked as expected. With the framework still set at 4.5, I re-introduced the errors and the code threw errors as applicable.

Please help, I need to fix this urgently.

Thanks,


Howto correctly parse using XElement.Parse() for strings that contain newline character in attributes

$
0
0
Hi,
I am using Linq to XML related classes for processing of XML that i get from a web server. Using the System.Net.HttpWebRequest and related classes i can successfully get the xml as a string. Now, want to convert the string i get into XElement (or XDocument), for which i am using XElement.Parse(string text) method. Then i display the values of some attributes in textboxes.

I had no problems until i found a subtle bug. The problem is that sometimes the WebServer sends XML which has a newline character in some attributes. To give an example the server sends something like this:
<?xml version="1.0" ?><Items><Item Name=\"Item1\" Description=\"First Item\"/><Item Name=\"Item2\" Description=\"Item with \n newline\"/></Items>
If you look at the description of the second item you will see that there is a newline character \n in it. I found out that the server is sending 0x0D 0x0A (carriage return, line feed) sequence which the text visualiser correctly displays as newline.

Now when i try to parse it into xml using XElement.Parse(string text) then i see that the \n has been converted into a space i.e. 0x20 char. So whenever i try to display the value of the Description in a TextBox using something like

int i = 0;
XElement itemElement = XElement.Parse(serverString);
foreach(XElement itemElement in itemElement.Elements("Item"))
{
     string description = (string)itemElement.Attribute("Description");
     TextBoxList[i].Text = descriptionText;
     i++;

}
I get a space instead of a newline in the TextBox. This is because of the \n to 'space' conversion while Xelement.Parse is used.

I know that the WebSever should have send &#xA; instead of a \n but is there a way to fix it ?

I used String.Replace() to replace all \n with &#xA; but it also relpaces any \n outside the attribute so my original xml becomes
<?xml version="1.0" ?>&#xA;<Items>&#xA;<Item Name=\"Item1\" Description=\"First Item\"/>&#xA;<Item Name=\"Item2\" Description=\"Item with &#xA; newline\"/>&#xA;</Items>
so it does not parse due to &#xA; present outside the attributes.
Also, it is surprising that the XAttribute does not seem to have this problem
XAttribute xa = new XAttribute("Description", "Item with \n newline");
string attributeValue = (string)xa.Value;
this code works perfectly and value of attributeValue is Item with \n newline . Is there any way out of this ?

There is an error in the XML document

$
0
0
Good Morning

I'm having trouble deserializing this document and give me the following error:
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.002.001.03"> It was not waiting

This is the document I want to deserialize:
<?xml version="1.0" encoding= "UTF-8" ?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.002.001.03">
<CstmrPmtStsRpt>
<GrpHdr>
<MsgId>xxxx/2018-03-16T01:21:33</MsgId>
<CreDtTm>2018-03-16T01:21:33</CreDtTm>
</GrpHdr>
<OrgnlGrpInfAndSts>
<OrgnlMsgId>xxxxDD106</OrgnlMsgId>
<OrgnlMsgNmId>Pain.008.001.02</OrgnlMsgNmId>
<OrgnlNbOfTxs>xxx</OrgnlNbOfTxs>
<OrgnlCtrlSum>xxxxx.xx</OrgnlCtrlSum>
<StsRsnInf>
<Rsn><Prtry>M001</Prtry></Rsn>
</StsRsnInf>
</OrgnlGrpInfAndSts>
<OrgnlPmtInfAndSts>
<OrgnlPmtInfId>DD001</OrgnlPmtInfId>
<OrgnlNbOfTxs>xxx</OrgnlNbOfTxs>
<OrgnlCtrlSum>xxxxx.xx</OrgnlCtrlSum>
<StsRsnInf>
<Rsn><Prtry>L001</Prtry></Rsn>
</StsRsnInf>
<TxInfAndSts>
<StsId>301</StsId>
<OrgnlEndToEndId>2IC 18100283</OrgnlEndToEndId>
<StsRsnInf>
<Rsn><Cd>0000</Cd></Rsn>
</StsRsnInf>
<AcctSvcrRef>xxxx/301/xxxxxxxxxx/xxxxx/M/F</AcctSvcrRef>
<OrgnlTxRef>
<Amt>
<InstdAmt Ccy="EUR">x.xx</InstdAmt>                                                                                                                   
</Amt>
<ReqdColltnDt>2018-03-15</ReqdColltnDt>
<CdtrSchmeId>
<Id>
<PrvtId>
<Othr>
<Id>xxxxxxxxxxxxxxx</Id>
</Othr>
</PrvtId>
</Id>
</CdtrSchmeId>
<PmtTpInf>
<SeqTp>FRST</SeqTp>
</PmtTpInf>
<PmtMtd>DD</PmtMtd>
<MndtRltdInf>
<MndtId>xxxxxxxxxxx</MndtId>
<DtOfSgntr>2018-03-13</DtOfSgntr>
<AmdmntInd>False</AmdmntInd>
</MndtRltdInf>
<Dbtr><Nm>xxxxxxxxx xxxxxxxxx xxxxxxx</Nm></Dbtr>
<DbtrAcct>
<Id>
<IBAN>xxxxxxxxxxxxxxxxxxxxxxxxx</IBAN>
</Id>
</DbtrAcct>
<DbtrAgt>
<FinInstnId><BIC>XXXXXXXXXXXXXX</BIC></FinInstnId>
</DbtrAgt>
<CdtrAgt>
<FinInstnId><BIC>XXXXXXXXXXXXXX</BIC></FinInstnId>
</CdtrAgt>
<Cdtr><Nm>xxxxxxxxxxxxx</Nm></Cdtr>
<CdtrAcct>
<Id>
<IBAN>xxxxxxxxxxxxxxxxxxxxxxxxx</IBAN>
</Id>
</CdtrAcct>
</OrgnlTxRef>
</TxInfAndSts>
...

</OrgnlPmtInfAndSts>
</CstmrPmtStsRpt>
</Document>

Any help thank you

my code in C#
public Document_EPC ReadReturnSepaXML(string filename)
        {

            string path = @"C:\Users\jcosta\Desktop\Testa_XSD\PrcessarRetorno\FicheiroSepaExemplo\" + filename + ".xml";
            
            try
            {
                using (System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    XmlSerializer documentRetornoSEPA = new XmlSerializer(typeof(Document_EPC));
                        return (Document_EPC)documentRetornoSEPA.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            //return myObjects;

        }

Prevent XML eXternal Entity (XXE) attack during deserialization

$
0
0

We are doing  security analysis of our code using veracode and its showing XXE flaw for below code, specifically where Deserialize() is invoked. How can we prevent serializer from accessing external entities. My attempt below is not working.

public

staticT DeserializeObject(stringxml,stringNamespace)

        {

            System.Xml.Serialization.

XmlSerializerserializer =newSystem.Xml.Serialization.XmlSerializer(typeof(T), Namespace);

           

MemoryStreamstream =

                   

newMemoryStream(Encoding.Default.GetBytes(xml));

           

XmlReaderSettingssettings =newXmlReaderSettings();

           

// allow entity parsing but do so more safely


            settings.DtdProcessing =

DtdProcessing.Ignore;

            settings.XmlResolver =

null;

           

using(XmlReaderreader = XmlReader.Create(stream, settings))

            {

               

returnserializer.Deserialize(reader)asT;

            }

        }


How to design two root elements with same name

$
0
0

File1:TRAData.xml

<GeneralTrainTimeTableList>
   <TrainTimeTables>
   <TrainTimeTable>
   <TrainInfo>
<TrainNo>51</TrainNo>
<RouteID>WL-M</RouteID>
<Direction>1</Direction>
<TripHeadSign>ToKaihsiung</TripHeadSign>
<OverNightStationID>1001</OverNightStationID>
<TripLine>1</TripLine>
<WheelChairFlag>0</WheelChairFlag>
<PackageServiceFlag>0</PackageServiceFlag>
<DiningFlag>0</DiningFlag>
<BreastFeedFlag>0 </BreastFeedFlag>
<BikeFlag>0</BikeFlag>
        <DailyFlag>1</DailyFlag>
        <ExtraTrainFlag>0</ExtraTrainFlag>
        <Note>每日行駛。莒光號自由行,不發售團體票及無座票。另不提供TR-PASS學生版搭乘。</Note>
      </TrainInfo>
   </TrainTimeTable>
   </TrainTimeTables>
</GeneralTrainTimeTableList>



File2:THSRData.xml

<GeneralTrainTimeTableList>
   <TrainTimetables>
   <TrainTimeTable>
      <TrainInfo> 
         <TrainNo>583</TrainNo>
         <RouteID>HSRL</RouteID>
         <Direction>0</Direction>
         <TripHeadSign>往左營<TripHeadSign>
       </TrainInfo>
   </TrainTimeTable>
   </TrainTimetables>
</GeneralTrainTimeTableList>


File: TRA.xsd

<xs:element name="GeneralTrainTimeTableList" type="TRAGeneralTrainTimeTableListType">
</xs:element>


File: THSR.xsd

<xs:element name="GeneralTrainTimeTableList" type="THSRGeneralTrainTimeTableListType">
</xs:element>


The problem is both of TRA.xsd and THSR.xsd include the same xsd (Rail.xsd),so the result comes out "GeneralTrainTimeTableList" is already declared in the TRA.xsd, "GeneralTrainTimeTableList" can't  declared again in the THSR.xsd .

The tag is being removed when I update the Inner Text

$
0
0

I am trying to go into a specific node and update the <Sql> tag.

I can update the inner text, but then it is leaving off the <Sql> tag which is then causing the Query to not be there.

What am I doing wrong?

  foreach (XmlNode item in nodes)
                        {
                            if (item != null)
                            {
                                if (item.FirstChild != null)
                                {
                                    if (string.IsNullOrWhiteSpace(item.FirstChild.Name) == false)
                                    {
                                        if (item.FirstChild.Name == "Sql")
                                        {
                                            item.InnerText = await serviceQueryFilter.InjectOrganizationFilter(userId, Id, item.InnerText).ConfigureAwait(false);

                                            item.InnerText = "<Sql>" + item.InnerText + "</Sql>"; // This is wrong, but after updating the text how do I re apply the <Sql></Sql>
                                        }
                                    }
                                }
                            }
                        }

How to properly cycle a XML Node of "Query"

$
0
0

I need to cycle a XML node called "Query" and pull the InnerText of all <Sql> or <StoreProcedure> notes underneath them.

There could be 10 <Sql> or <StoredProcedure> nodes underneath.

What is the best way to do that using LINQ?

I have this so far:

XmlNodeList nodes = root.SelectNodes("//Query");

foreach (XmlNode item in nodes)
                        {
                            if (item != null)
                            {
                                if (item.FirstChild != null)
                                {
                                    if (string.IsNullOrWhiteSpace(item.FirstChild.Name) == false)
                                    {
                                        if (item.FirstChild.Name == "Sql")
                                        {
                                        }
                                    }
                                }
                            }
                        }

Import string of XML into XML Document

$
0
0

I have a template xml string that I read from a db, I have then to insert xml strings from many transaction records into that document.  Here's a very cut down template..

<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope"><Body><IRenvelope xmlns="http://www.govtalk.gov.uk/taxation/PAYE/RTI/FullPaymentSubmission/13-14/2"><FullPaymentSubmission /></IRenvelope></Body></GovTalkMessage>

The transactional xml text needs to be added to the FullPaymentSubmission element..  Here's an example segment..

<Employee><EmployeeDetails><NINO>AA123456A</NINO><Name><Ttl>Mr</Ttl><Fore>Anthony</Fore><Sur>Brewer</Sur></Name></EmployeeDetails></Employee>

So the document should look like this.. 

<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope"><Body><IRenvelope xmlns="http://www.govtalk.gov.uk/taxation/PAYE/RTI/FullPaymentSubmission/13-14/2"><FullPaymentSubmission><Employee><EmployeeDetails><NINO>AA123456A</NINO><Name><Ttl>Mr</Ttl><Fore>Anthony</Fore><Sur>Brewer</Sur></Name></EmployeeDetails></Employee></FullPaymentSubmission></IRenvelope></Body></GovTalkMessage>

So, I tried the following code..

        Dim xBody, xTemp As XmlDocument
        Dim xEmp As XmlNode
        Dim xNode As XmlNode
        Dim strBody As String = "<GovTalkMessage xmlns=""http://www.govtalk.gov.uk/CM/envelope""><Body><IRenvelope xmlns=""http://www.govtalk.gov.uk/taxation/PAYE/RTI/FullPaymentSubmission/13-14/2""><FullPaymentSubmission /></IRenvelope></Body></GovTalkMessage>"
        Dim strEmp As String = "<Employee><EmployeeDetails><NINO>AA123456A</NINO><Name><Ttl>Mr</Ttl><Fore>Anthony</Fore><Sur>Brewer</Sur></Name></EmployeeDetails></Employee>"
        Dim GovTalkMessageNS As String
        Dim IRenvelopeNS As String

        xBody = New XmlDocument
        xBody.LoadXml(strBody)

        xTemp = New XmlDocument
        xTemp.LoadXml(strEmp)
        xEmp = xTemp.FirstChild

        ' find the namespace of the GovTalkMessage element (have to skip any number of comments)
        For Each xNode In xBody.ChildNodes
            If xNode.Name = "GovTalkMessage" Then
                GovTalkMessageNS = xNode.Attributes("xmlns").Value
                Exit For
            End If
        Next
        If GovTalkMessageNS = String.Empty Then
            Throw New Exception("Badly formed XML")
        End If

        ' Create a namespace manager for the namespace
        Dim nsmgr As New XmlNamespaceManager(xBody.NameTable)
        nsmgr.AddNamespace("gt", GovTalkMessageNS)
        IRenvelopeNS = xBody.SelectSingleNode("//gt:Body", nsmgr).FirstChild.Attributes("xmlns").Value
        nsmgr.AddNamespace("ir", IRenvelopeNS)

        xNode = xBody.SelectSingleNode("//ir:FullPaymentSubmission", nsmgr)

        xNode.AppendChild(xNode.OwnerDocument.ImportNode(xEmp, True))

Which does add the <employee> node to the correct element, but, it adds a default namespace attribute..

<IRenvelope xmlns="http://www.govtalk.gov.uk/taxation/PAYE/RTI/FullPaymentSubmission/13-14/2"><FullPaymentSubmission><Employee xmlns=""><EmployeeDetails>
How do I get rid of that extra attribute ?


Viewing all 935 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>