Setting XML namespaces with the System.Xml.Linq API - c#

I'm having trouble generating XML along the lines of this:
<Root xmlns:brk="http://somewhere">
<child1>
<brk:node1>123456</brk:node1>
<brk:node2>500000000</brk:node2>
</child1>
</Root>
This code get me most of the way, but I can't get the 'brk' namespace in front of the nodes;
var rootNode = new XElement("Root");
rootNode.Add(new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere"));
var childNode = new XElement("child1");
childNode.Add(new XElement("node1",123456));
rootNode.Add(childNode);
I've tried this:
XNamespace brk = "http://somewhere";
childNode.Add(new XElement(brk+"node1",123456));
and this
XNamespace brk = "http://somewhere";
childNode.Add(new XElement("brk:node1",123456));
but both cause exceptions.

You are almost there, but you made one simple error in your first code example. I believe this is what you require:
XNamespace brk = "http://somewhere.com";
XElement root = new XElement("Root",
new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
XElement childNode = new XElement("child1");
childNode.Add(new XElement(brk + "node1",123456));
root.Add(childNode);
The main difference here is where I add node1 to childNode as follows:
childNode.Add(new XElement(brk + "node1",123456));
This code, given an XmlWriter and XDocument gives me the output:
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:brk="http://somewhere.com">
<child1>
<brk:node1>123456</brk:node1>
</child1>
</Root>
See MSDN for details of using XNamespace.

I believe the problem is that the root element needs to have the namespace as well:
XElement root = new XElement("Root",
new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
needs to be:
XElement root = new XElement(brk + "Root",
new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));

This is solotuion and working fine.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Serialization;
namespace CreateSampleXML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
XNamespace xm = "http://somewhere.com";
XElement rt= new XElement("Root", new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
XElement cNode = new XElement("child1");
cNode.Add(new XElement(xm + "node1", 123456));
cNode.Add(new XElement(xm + "node2", 500000000));
rt.Add(cNode);
XDocument doc2 = new XDocument(rt);
doc2.Save(#"C:\sample3.xml");
}
}
}

Related

creating xml header as in example

I am bad at xml understanding, please help me
this is xml that I need
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:ENRC-IDOC_939_DigiDocs:idm">
<soapenv:Header />
<soapenv:Body>
<urn:mt_digidocs_fees>
This is my code
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
XmlElement envelope = doc.CreateElement("soapenv","Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
XmlAttribute urn = doc.CreateAttribute("xmlns","urn", "http://www.w3.org/2000/xmlns/");
urn.Value = "urn:ENRC-IDOC_939_DigiDocs:idm";
envelope.Attributes.SetNamedItem(urn);
doc.AppendChild(envelope);
XmlNode soapenvheader = doc.CreateElement("soapenv", "Header", doc.DocumentElement.NamespaceURI);
envelope.AppendChild(soapenvheader);
XmlNode body = doc.CreateElement("soapenv", "Body", doc.DocumentElement.NamespaceURI);
envelope.AppendChild(body);
XmlElement mt_digidocs_fees = doc.CreateElement("mt_digidocs_fees");
mt_digidocs_fees.Prefix = "urn";
body.AppendChild(mt_digidocs_fees);
and this is what I get
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:urn="urn:ENRC-IDOC_939_DigiDocs:idm" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header />
<soapenv:Body>
<mt_digidocs_fees>
So there last Element's name does not contain prefix and namespace addresses are in different order
Thanks in advance
I like using Xml Linq like this :
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 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:ENRC-IDOC_939_DigiDocs:idm\"></soapenv:Envelope>";
XDocument doc = XDocument.Parse(ident);
XElement envelope = doc.Root;
XNamespace nsUrn = envelope.GetNamespaceOfPrefix("urn");
XNamespace nsSoapenv = envelope.GetNamespaceOfPrefix("soapenv");
XElement header = new XElement(nsSoapenv + "Header");
envelope.Add(header);
XElement body = new XElement(nsSoapenv + "Body");
envelope.Add(body);
XElement fees = new XElement(nsUrn + "mt_digidocs_fees");
body.Add(fees);
}
}
}

Convert XML to formatted plain text issue

I have the following XML and i want to convert the contents to something along the lines of the following format.
PatientId: 123455, IdScheme: Test ....
<?xml version="1.0"?>
<gls:TheDocument xmlns:pbr="http://www.something.com"
xmlns:gls="http://www.testsomething.com"
xmlns:cnr="http://www.organisation.com"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="2.8">
<gls:PatientDem>
<cnr:PatientId>
<cnr:IdValue>123455</cnr:IdValue>
<cnr:IdScheme>TEST</cnr:IdScheme>
<cnr:IdType>PRN</cnr:IdType>
</cnr:PatientId>
<cnr:PatientName>
<cnr:Name>
<cnr:Title>Mr</cnr:Title>
<cnr:GivenName>Joe</cnr:GivenName>
<cnr:FamilyName>Wood</cnr:FamilyName>
</cnr:Name>
<cnr:NameType>Current Name</cnr:NameType>
</cnr:PatientName>
<cnr:PatientAddress>
<cnr:Address>
<cnr:AddressLine>57 High Street</cnr:AddressLine>
<cnr:AddressLine>London</cnr:AddressLine>
</cnr:Address>
<cnr:PostCode>WC1E 7HU</cnr:PostCode>
<cnr:AddressType>Current Residence</cnr:AddressType>
</cnr:PatientAddress>
<cnr:DateOfBirth>1969-11-02</cnr:DateOfBirth>
<cnr:Sex>M</cnr:Sex>
</gls:PatientDem>
<pbr:PatientAdminRef>
<pbr:Referrer>
<pbr:RefGP>
<cnr:GpcpName>
<cnr:FullName>DR SMITH</cnr:FullName>
</cnr:GpcpName>
<cnr:TheOrganisation>
<cnr:OrganisationId>
<cnr:IdValue>52522</cnr:IdValue>
<cnr:IdScheme>PracticeID</cnr:IdScheme>
<cnr:IdType>Healthcare Organisation</cnr:IdType>
</cnr:OrganisationId>
<cnr:OrganisationName>National Health
Service</cnr:OrganisationName>
<cnr:OrganisationAddress>
<cnr:TheAddress>
<cnr:AddressLine1>Centre House</cnr:AddressLine1>
<cnr:AddressLine2>799 Chichester
Street</cnr:AddressLine2>
<cnr:AddressLine3>London</cnr:AddressLine3>
</cnr:TheAddress>
<cnr:AddressType>Practice Address</cnr:AddressType>
</cnr:OrganisationAddress>
<cnr:OrganisationTelecom>
<cnr:TelephoneNumber>016190542350</cnr:TelephoneNumber>
<cnr:TeleType>Voice</cnr:TeleType>
</cnr:OrganisationTelecom>
</cnr:TheOrganisation>
</pbr:RefGP>
</pbr:Referrer>
</pbr:PatientAdminRef>
</gls:TheDocument>
So is it possible to do this? I had a go at doing this but I know for a fact i am doing it wrong as it cannot produce the result i want so any help will be much appreciated:
C# Code
XDocument doc = XDocument.Parse(xml);
XElement root = doc.Root;
XNamespace glsNs = root.GetNamespaceOfPrefix("gls");
XNamespace cnrNS = root.GetNamespaceOfPrefix("cnr");
XNamespace pbrNS = root.GetNamespaceOfPrefix("pbr");
var output = new StringBuilder();
foreach (var result in doc.Descendants(gls + "PatientDem").Select(x => new {
Key = (string)x.Name.LocalName,
Value = x.Value
}))
{
output.AppendLine($"{result.key} : {result.value}");
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace cnrNs = root.GetNamespaceOfPrefix("cnr");
var results = doc.Descendants(cnrNs + "PatientId").Select(x => new {
value = (string)x.Element(cnrNs + "IdValue"),
scheme = (string)x.Element(cnrNs + "IdScheme")
}).ToList();
}
}
}

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");
}
}
}

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