Create xml like example below and make a request - c#

I need to create an xml which it will look like xml below:
<?xml version="1.0"?>
-<env:Envelope xmlns:ns3="http://rgwspublic2/RgWsPublic2" xmlns:ns2="http://rgwspublic2/RgWsPublic2Service" xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:env="http://www.w3.org/2003/05/soap-envelope">
-<env:Header>
-<ns1:Security>
-<ns1:UsernameToken>
<ns1:Username>xxxx</ns1:Username>
<ns1:Password>yyyy</ns1:Password>
</ns1:UsernameToken>
</ns1:Security>
</env:Header>
-<env:Body>
-<ns2:rgWsPublic2AfmMethod>
-<ns2:INPUT_REC>
<ns3:afm_called_by/>
<ns3:afm_called_for>xxxxxxxxx</ns3:afm_called_for>
</ns2:INPUT_REC>
</ns2:rgWsPublic2AfmMethod>
</env:Body>
</env:Envelope>
I am new in xmls. How can i create an xml like this?
Also if is it easier to create an xml from a list collection?
Then i try to make a request like example below
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("https://www1.gsis.gr:443", new StringContent(booksFromFile.ToString(), Encoding.UTF8, "application/xml"));
var HttpResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine(HttpResponse);
But i am getting error
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="REFRESH" content="0;url=http://www.gsis.gr"></HEAD>
<BODY>
</BODY>
</HTML>

Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml = "<?xml version=\"1.0\"?>" +
"<env:Envelope" +
" xmlns:ns3=\"http://rgwspublic2/RgWsPublic2\"" +
" xmlns:ns2=\"http://rgwspublic2/RgWsPublic2Service\"" +
" xmlns:ns1=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"" +
" xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\">" +
"</env:Envelope>";
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace nsEnv = root.GetNamespaceOfPrefix("env");
XNamespace ns1 = root.GetNamespaceOfPrefix("ns1");
XNamespace ns2 = root.GetNamespaceOfPrefix("ns2");
XNamespace ns3 = root.GetNamespaceOfPrefix("ns3");
XElement header = new XElement(nsEnv + "Header",
new XElement(ns1 + "Security",
new XElement(ns1 + "UsernameToken")));
XElement usernameToken = header.Descendants(ns1 + "UsernameToken").FirstOrDefault();
string username = "xxxxx";
string password = "yyyy";
usernameToken.Add(new XElement(ns1 + "Username", username));
usernameToken.Add(new XElement(ns1 + "Password", password));
root.Add(header);
XElement body = new XElement(nsEnv + "Body",
new XElement(ns2 + "rgWsPublic2AfmMethod",
new XElement(ns2 + "INPUT_REC")));
XElement inputRec = body.Descendants(ns2 + "INPUT_REC").FirstOrDefault();
root.Add(body);
string afmCalledFor = "xxxxxxxxx";
inputRec.Add(new XElement(ns3 + "afm_called_by"));
inputRec.Add(new XElement(ns3 + "afm_called_for", afmCalledFor));
}
}
}

Related

Create XML from SQL select query

I am trying to create a xml from a SQL select, but I can not insert ":" (like cac:PartyTaxScheme), neither can put 2 data in one element, look element "cbc:CompanyID" (<cbc:CompanyID schemeName="31" schemeID="0" schemeAgencyID="195">900711000</cbc:CompanyID> ), how can I do it ?
Next is the example I want to expect:
<cac:PartyTaxScheme>
<cbc:RegistrationName>GRUPO FAM</cbc:RegistrationName>
<cbc:CompanyID schemeName="31" schemeID="0" schemeAgencyID="195">900711000</cbc:CompanyID>
<cbc:TaxLevelCode listName="48">O-23</cbc:TaxLevelCode>
<cac:RegistrationAddress>
<cbc:ID>11001</cbc:ID>
<cbc:CountrySubentityCode>11</cbc:CountrySubentityCode>
<cac:AddressLine>
<cbc:Line>CaLL 90</cbc:Line>
</cac:AddressLine>
<cac:Country>
<cbc:IdentificationCode>CO</cbc:IdentificationCode>
</cac:Country>
</cac:RegistrationAddress>
</cac:PartyTaxScheme>
Thanks a lot
Using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<cac:PartyTaxScheme xmlns:cac=\"URL1\" xmlns:cbc=\"URL2\">" +
"</cac:PartyTaxScheme>";
XDocument doc = XDocument.Parse(ident);
string registrationName = "GPUPO FAM";
string schemeName = "31";
string schemeID = "0";
string schemeAgencyID = "195";
string companyID = "900711000";
string listName = "48";
string taxLevelCode = "0-23";
string ID = "11001";
string countrySubentityCode = "11";
string address = "CaLL 90";
string identificationCode = "CO";
XElement partyTaxScheme = doc.Root;
XNamespace nsCac = partyTaxScheme.GetNamespaceOfPrefix("cac");
XNamespace nsCbc = partyTaxScheme.GetNamespaceOfPrefix("cbc");
XElement xRegistrationName = new XElement(nsCac + "RegistrationName", registrationName);
partyTaxScheme.Add(xRegistrationName);
XElement xCompanyID = new XElement(nsCbc + "CompanyID", new object[] {
new XAttribute("scnemeName", schemeName),
new XAttribute("schemeID", schemeID),
new XAttribute("schemeAgencyID", schemeAgencyID),
companyID
});
partyTaxScheme.Add(xCompanyID);
XElement xTaxLevelCode = new XElement(nsCbc + "TaxLevelCode", new object[] {
new XAttribute("listName", listName),
taxLevelCode
});
partyTaxScheme.Add(xTaxLevelCode);
XElement xRegistrationAddress = new XElement(nsCac + "RegistrationAddress");
partyTaxScheme.Add(xRegistrationAddress);
xRegistrationAddress.Add(new XElement(nsCbc + "ID", ID));
xRegistrationAddress.Add(new XElement(nsCbc + "CountrySubentityCode", countrySubentityCode));
xRegistrationAddress.Add(new XElement(nsCac + "AddressLine", new XElement(nsCbc + "Line", address)));
xRegistrationAddress.Add(new XElement(nsCac + "Country", new XElement(nsCbc + "IdentificationCode", countrySubentityCode)));
}
}
}

Get value from simple XML document

I have the following XML
<User
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models">
<Game_ID>3</Game_ID>
<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>
<UserName>tony2</UserName>
<User_ID>16</User_ID>
</User>
Using C# I am loading this into an XMLDocument, How do I retrieve the UserGUID value?
Leveraging System.Xml.Linq you could do
string xml = "..."; // your inline XML
var doc = System.Xml.Linq.XDocument.Parse(xml);
or
string xmlFile = "..."; // your XML filename
var doc = System.Xml.Linq.XDocument.Load(xmlFile);
and then, to get the UserGUID
var userGuid = doc.Descendants().Where(x=>x.Name.LocalName == "UserGUID").First().Value;
This will work for you.
string xml = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models\">" +
"<Game_ID>3</Game_ID>" +
"<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>" +
"<UserName>tony2</UserName>" +
"<User_ID>16</User_ID>" +
"</User>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var id = doc.GetElementsByTagName("UserGUID")[0].InnerText;
You need to use the namespace. I often use mipnw approach (probably stole idea from one of my postings). See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement user = doc.Root;
XNamespace ns = user.GetDefaultNamespace();
string UserGUID = (string)user.Element(ns + "UserGUID");
}
}
}

How to read xml file in c# with specific attribute

I have an xml file with attribute
xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"
My C# code:
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
.SelectSingleNode("/BookingCreate/CommitLevel")
.InnerText;
My XML:
<BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
<Authority>
<Org>danco</Org>
<User>xmltest</User>
<Password>xmltest</Password>
<Language>en</Language>
<Currency>EUR</Currency>
<TestDebug>false</TestDebug>
<Version>1.26</Version>
</Authority>
<QuoteId>17081233-3</QuoteId>
<HotelStayDetails>
<Room>
<Guests>
<Adult title="Mr" first="djkvb" last="jkj" />
<Adult title="Mr" first="jfs" last="kjdjs" />
</Guests>
</Room>
</HotelStayDetails>
<HotelSearchCriteria>
<AvailabilityStatus>allocation</AvailabilityStatus>
<DetailLevel>basic</DetailLevel>
</HotelSearchCriteria>
<CommitLevel>prepare</CommitLevel>
</BookingCreate>
What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.
You need to specify the namespace, by using a namespace manager. This should work
XmlDocument bookingXml = new XmlDocument();
bookingXml.Load("PrepareBooking.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(bookingXml.NameTable);
ns.AddNamespace("booking", "http://www.reservwire.com/namespace/WebServices/Xml");
var commitLevel = bookingXml.SelectSingleNode("//booking:BookingCreate//booking:CommitLevel", ns).InnerText;
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement bookingCreate = doc.Descendants().Where(x => x.Name.LocalName == "BookingCreate").FirstOrDefault();
XNamespace ns = bookingCreate.GetDefaultNamespace();
var results = doc.Descendants(ns + "BookingCreate").Select(x => new {
org = (string)x.Descendants(ns + "Org").FirstOrDefault(),
user = (string)x.Descendants(ns + "User").FirstOrDefault(),
password = (string)x.Descendants(ns + "Password").FirstOrDefault(),
language = (string)x.Descendants(ns + "Language").FirstOrDefault(),
currency = (string)x.Descendants(ns + "Currency").FirstOrDefault(),
testDebug = (Boolean)x.Descendants(ns + "TestDebug").FirstOrDefault(),
version = (string)x.Descendants(ns + "Version").FirstOrDefault(),
quoteId = (string)x.Element(ns + "QuoteId"),
guests = x.Descendants(ns + "Adult").Select(y => new {
title = (string)y.Attribute("title"),
first = (string)y.Attribute("first"),
last = (string)y.Attribute("last")
}).ToList(),
availability = (string)x.Descendants(ns + "AvailabilityStatus").FirstOrDefault(),
detailLevel = (string)x.Descendants(ns + "DetailLevel").FirstOrDefault()
}).FirstOrDefault();
}
}
}

c# how to create XML file with XSD schemas

<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<ftc:FATCA_OECD version="2.0" xsi:schemaLocation="urn:oecd:ties:fatca:v2 FatcaXML_v2.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ftc="urn:oecd:ties:fatca:v2" xmlns:sfa="urn:oecd:ties:stffatcatypes:v2">
<ftc:MessageSpec>
<sfa:SendingCompanyIN>S519K4.99999.SL.392</sfa:SendingCompanyIN>
<sfa:TransmittingCountry>JP</sfa:TransmittingCountry>
<sfa:ReceivingCountry>US</sfa:ReceivingCountry>
<sfa:MessageType>FATCA</sfa:MessageType>
<sfa:MessageRefId>DBA6455E-8454-47D9-914B-FEE48E4EF3AA</sfa:MessageRefId>
<sfa:ReportingPeriod>2016-12-31</sfa:ReportingPeriod>
<sfa:Timestamp>2017-01-17T09:30:47Z</sfa:Timestamp>
</ftc:MessageSpec>
</ftc:FATCA_OECD>
my code:
XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
XmlElement element1 = doc.CreateElement("<ftc:FATCA_OECD version=\"2.0\" xsi:schemaLocation=\"urn:oecd:ties:fatca:v2 FatcaXML_v2.0.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ftc=\"urn:oecd:ties:fatca:v2\" xmlns:sfa=\"urn:oecd:ties:stffatcatypes:v2\">");
doc.AppendChild(element1);
XmlElement element2 = doc.CreateElement("ftc:MessageSpec");
element1.AppendChild(element2);
XmlElement element3 = doc.CreateElement("sfa:SendingCompanyIN");
XmlText text1 = doc.CreateTextNode(txt_SendingCompanyIN.Text);
element3.AppendChild(text1);
element2.AppendChild(element3);
XmlElement element4 = doc.CreateElement("sfa:TransmittingCountry");
XmlText text2 = doc.CreateTextNode(txt_TransmittingCountry.Text);
element4.AppendChild(text2);
element2.AppendChild(element4);
XmlElement element5 = doc.CreateElement("sfa:ReceivingCountry");
XmlText text3 = doc.CreateTextNode(txt_ResCountryCode.Text);
element4.AppendChild(text3);
element2.AppendChild(element4);
I need to create the following XML and I'm trying to do this using XDocument. but fail cannot create xml file?
how can i create a xsd schema for this xml file?
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication48
{
class Program
{
static void Main(string[] args)
{
//<?xml version="1.0" encoding="UTF-8"?>
//<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
//<ftc:FATCA_OECD version="2.0" xsi:schemaLocation="urn:oecd:ties:fatca:v2 FatcaXML_v2.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ftc="urn:oecd:ties:fatca:v2" xmlns:sfa="urn:oecd:ties:stffatcatypes:v2">
// <ftc:MessageSpec>
// <sfa:SendingCompanyIN>S519K4.99999.SL.392</sfa:SendingCompanyIN>
// <sfa:TransmittingCountry>JP</sfa:TransmittingCountry>
// <sfa:ReceivingCountry>US</sfa:ReceivingCountry>
// <sfa:MessageType>FATCA</sfa:MessageType>
// <sfa:MessageRefId>DBA6455E-8454-47D9-914B-FEE48E4EF3AA</sfa:MessageRefId>
// <sfa:ReportingPeriod>2016-12-31</sfa:ReportingPeriod>
// <sfa:Timestamp>2017-01-17T09:30:47Z</sfa:Timestamp>
// </ftc:MessageSpec>
//</ftc:FATCA_OECD>
string header =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ftc:FATCA_OECD" +
" version=\"2.0\" xsi:schemaLocation=\"urn:oecd:ties:fatca:v2 FatcaXML_v2.0.xsd\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:ftc=\"urn:oecd:ties:fatca:v2\"" +
" xmlns:sfa=\"urn:oecd:ties:stffatcatypes:v2\">" +
"</ftc:FATCA_OECD>";
XDocument doc = XDocument.Parse(header);
XElement FATCA_OECD = (XElement)doc.FirstNode;
XNamespace ftcNS = FATCA_OECD.GetNamespaceOfPrefix("ftc");
XNamespace sfaNS = FATCA_OECD.GetNamespaceOfPrefix("sfa");
XElement MessageSpec = new XElement(ftcNS + "MessageSpec", new object[] {
new XElement(sfaNS + "SendingCompanyIN", "S519K4.99999.SL.392"),
new XElement(sfaNS + "TransmittingCountry", "JP"),
new XElement(sfaNS + "ReceivingCountry", "US"),
new XElement(sfaNS + "MessageType", "FATCA"),
new XElement(sfaNS + "MessageRefId", "DBA6455E-8454-47D9-914B-FEE48E4EF3AA"),
new XElement(sfaNS + "ReportingPeriod", "2016-12-31"),
new XElement(sfaNS + "Timestamp", "2017-01-17T09:30:47Z"),
});
FATCA_OECD.Add(MessageSpec);
}
}
}

Complex Xml namespaces in c#

I am trying to create an xml with multiple namespaces in c#.
I am using LINQ XDocument object to create xml.
The multiple namespaces of xml are causing a lot of confusion.
Can anyone help me out on right direction please.
<?xml version="1.0" encoding="UTF-8"?>
<n1:Form109495CTransmittalUpstream
xmlns="urn:us:gov:treasury:irs:ext:aca:air:6.2" xmlns:irs="urn:us:gov:treasury:irs:common"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:n1="urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage"
xsi:schemaLocation="urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage IRS-Form1094-1095CTransmitterUpstreamMessage.xsd">
<Form1094CUpstreamDetail recordType="String" lineNum="0">
<SubmissionId>1</SubmissionId>
<irs:TaxYr>1000</irs:TaxYr>
<irs:CorrectedInd>true</irs:CorrectedInd>
</Form1094CUpstreamDetail>
</n1:Form109495CTransmittalUpstream>
C# Code
new XDocument(
new XAttribute(XNamespace.Xmlns + "version", "1.0"),
new XAttribute(XNamespace.Xmlns + "encoding", "UTF-8"),
new XElement("n1:Form109495CTransmittalUpstream","")
).Save("sample.xml");
As you may be aware, a 'qualified name' in XML is made up of the namespace and the local name. To make this easier to deal with, you include namespace declarations that prefix these namespaces.
So, for example, where you see irs:TaxYr, the qualified name is actually made up of the urn:us:gov:treasury:irs:common namespace and the TaxYr local name.
The prefix values themselves are pretty unimportant - they're just a lookup mechanism. LINQ to XML will handle this for you automatically (by generating unique prefixes, usually p1, p2 etc.), but you can include them as attributes yourself. To create such a declaration for the irs namespace you'd create the following attribute:
new XAttribute(XNamespace.Xmlns + "irs", "urn:us:gov:treasury:irs:common")
LINQ to XML also provides some nifty implicit conversions, allowing you to create an XNamespace and qualified XName implicitly from a string. So, to get your TaxYr name you'd do the following:
XNamespace irs = "urn:us:gov:treasury:irs:common";
XName taxYr = irs + "TaxYr";
Following this all the way through for each of your elements and attributes, your XML could be created declaratively like so:
XNamespace def = "urn:us:gov:treasury:irs:ext:aca:air:6.2";
XNamespace irs = "urn:us:gov:treasury:irs:common";
XNamespace n1 = "urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
var schemaHint = "urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage IRS-Form1094-1095CTransmitterUpstreamMessage.xsd";
var doc = new XDocument(
new XElement(n1 + "Form109495CTransmittalUpstream",
new XAttribute("xmlns", def),
new XAttribute(XNamespace.Xmlns + "irs", irs),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(XNamespace.Xmlns + "n1", n1),
new XAttribute(xsi + "schemaLocation", schemaHint),
new XElement(def + "Form1094CUpstreamDetail",
new XAttribute("recordType", "String"),
new XAttribute("lineNum", 0),
new XElement(def + "SubmissionId", 1),
new XElement(irs + "TaxYr", 1000),
new XElement(irs + "CorrectedInd", true)
)
)
);
This is how I normally do it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<n1:Form109495CTransmittalUpstream" +
" xmlns=\"urn:us:gov:treasury:irs:ext:aca:air:6.2\" xmlns:irs=\"urn:us:gov:treasury:irs:common\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:n1=\"urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage\"" +
" xsi:schemaLocation=\"urn:us:gov:treasury:irs:msg:form1094-1095Ctransmitterupstreammessage IRS-Form1094-1095CTransmitterUpstreamMessage.xsd\">" +
"</n1:Form109495CTransmittalUpstream>";
XDocument doc = XDocument.Parse(xml);
XElement form109495CTransmittalUpstream = (XElement)doc.FirstNode;
XNamespace def = form109495CTransmittalUpstream.GetDefaultNamespace();
XNamespace irs = form109495CTransmittalUpstream.GetNamespaceOfPrefix("irs");
XNamespace n1 = form109495CTransmittalUpstream.GetNamespaceOfPrefix("n1");
XElement form1094CUpstreamDetail = new XElement(def + "Form1094CUpstreamDetail", new XAttribute[] {
new XAttribute("recordType", "String"), new XAttribute("lineNum", 0)
});
form109495CTransmittalUpstream.Add(form1094CUpstreamDetail);
form109495CTransmittalUpstream.Add(new XElement("SubmissionId", 1));
form109495CTransmittalUpstream.Add(new XElement(irs + "TaxYr", 1000));
form109495CTransmittalUpstream.Add(new XElement(irs + "CorrectedInd", true));
}
}
}
​

Categories