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);
}
}
}
Related
I'm trying to get the element values of the following XML document using LINQ but I'm getting "Object reference not set to an instance of an object.";
XML:
<soapenv:Envelope xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/
xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance>
<soapenv:Body>
<ns1:GetContactResponse soapenv:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ xmlns:ns1=http://DefaultNamespace>
<GetContactReturn xsi:type="ns2:Response" xmlns:ns2=http://getContact.contact.V300>
<Contact xsi:type="ns3:Contact" xmlns:ns3=http://_contact.contact.V300>
<Address xsi:type="xsd:string">123 test</Address>
<Address2 xsi:type="xsd:string"/>
<City xsi:type="xsd:string">Los Angeles</City>
<CountryCode xsi:type="xsd:string">US</CountryCode>
<StateCode xsi:type="xsd:string">CA</StateCode>
<ZipCode xsi:type="xsd:string">90001</ZipCode>
</Contact>
<Errors soapenc:arrayType="ns4:Error[0]" xsi:type="soapenc:Array" xmlns:ns4=http://response.base.V300 xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding//>
<IsSuccessful xsi:type="xsd:boolean">true</IsSuccessful>
<RecordCount xsi:type="xsd:double">1.0</RecordCount>
</GetContactReturn>
</ns1:GetContactResponse>
</soapenv:Body>
</soapenv:Envelope>
I'm using the following to loop through:
using (StreamReader rd = new StreamReader(services.GetResponseStream()))
{
var ServiceResult = rd.ReadToEnd();
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(ServiceResult);
var xDocResult = (from x in xdoc.Descendants("Contacts")
select new Location
{
Address = x.Element("Address").Value,
Address2 = x.Element("Address2").Value,
city = x.Element("City").Value,
statecode = x.Element("StateCode").Value,
zipcode = x.Element("ZipCode").Value
});
}
I'm assuming it's because there is no root. How do I get the values of the individual elements?
Your xml has lots of errors. I'm using StringReader. You should replace with StreamReader. Here is correction
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:GetContactResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://DefaultNamespace">
<GetContactReturn xsi:type="ns2:Response" xmlns:ns2="http://getContact.contact.V300">
<Contact xsi:type="ns3:Contact" xmlns:ns3="http://_contact.contact.V300">
<Address xsi:type="xsd:string">123 test</Address>
<Address2 xsi:type="xsd:string"/>
<City xsi:type="xsd:string">Los Angeles</City>
<CountryCode xsi:type="xsd:string">US</CountryCode>
<StateCode xsi:type="xsd:string">CA</StateCode>
<ZipCode xsi:type="xsd:string">90001</ZipCode>
</Contact>
<Errors soapenv:arrayType="ns4:Error[0]" xsi:type="soapenc:Array" xmlns:ns4="http://response.base.V300 xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding"/>
<IsSuccessful xsi:type="xsd:boolean">true</IsSuccessful>
<RecordCount xsi:type="xsd:double">1.0</RecordCount>
</GetContactReturn>
</ns1:GetContactResponse>
</soapenv:Body>
</soapenv:Envelope>
Here is the c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(xml);
XDocument doc = XDocument.Load(reader);
XElement contact = doc.Descendants().Where(x => x.Name.LocalName == "Contact").FirstOrDefault();
XNamespace ns = contact.GetDefaultNamespace();
string address = (string)contact.Element(ns + "Address");
string address2 = (string)contact.Element(ns + "Address2");
string city = (string)contact.Element(ns + "City");
string country = (string)contact.Element(ns + "CountryCode");
string state = (string)contact.Element(ns + "StateCode");
string zip = (string)contact.Element(ns + "ZipCode");
}
}
}
i create an XMLDocument:
`
XmlDocument doc = new XmlDocument();
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
// -----------------------create root-----------------------------
XmlElement rootnode = doc.CreateElement( "BMECAT");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
//Console.WriteLine(sb.ToString());
//get attribute for BmeCat
rootnode.SetAttribute("version", "2005");
XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
atr.Value = "http://www.adlnet.org/xsd/adlcp_v1p3";
rootnode.SetAttributeNode(atr);
rootnode.Attributes.Append(atr);`
then i convert it to XDocument using the function below but i get a NameSpace changed like this
XDocument ToXDocument(XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
`
below the xml and the XDocument
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" p1:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" xsi:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
You need to explicitly add the xsi namespace declaration manually at the beginning of your element.
Nodes are processed in document order and the namespace declaration appears later after it is first used. It doesn't know to use xsi for the prefix until it's too late.
var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = (XmlElement)doc.AppendChild(doc.CreateElement("BMECAT"));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
root.SetAttribute("xmlns:xsi", xsi); //set the namespace now
root.SetAttribute("schemaLocation", xsi, "http://www.adlnet.org/xsd/adlcp_v1p3");
root.SetAttribute("version", "2005");
<?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);
}
}
}
I want to add child node in existing xml
<tblTemp>
<Details>
<LoginId>4</LoginId>
<AId>2</AId>
<OId>763</OId>
<LDate>2016-09-26</LDate>
<LTime>15:27:39</LTime>
<ReasonId>1</ReasonId>
<Flag>2</Flag>
</Details>
<Details>
<LoginId>3</LoginId>
<AId>2</AId>
<OId>763</OId>
<LDate>2016-09-26</LDate>
<LTime>12:22:39</LTime>
<ReasonId>4</ReasonId>
<Flag>2</Flag>
</Details>
<Details>
<LoginId>1</LoginId>
<AId>1</AId>
<OId>765</OId>
<LDate>2016-09-26</LDate>
<LTime>10:22:39</LTime>
<ReasonId>4</ReasonId>
<Flag>2</Flag>
</Details>
</tblTemp>
And i want output like this
<tblTemp>
<Details>
<LoginId>4</LoginId>
<AId>2</AId>
<OId>763</OId>
<LDate>2016-09-26</LDate>
<LTime>15:27:39</LTime>
<FDate>2016-09-26</FDate>
<FTime>16:50:30</FTime>
<ReasonId>1</ReasonId>
<Flag>2</Flag>
</Details>
<Details>
<LoginId>3</LoginId>
<AId>2</AId>
<OId>763</OId>
<LDate>2016-09-26</LDate>
<LTime>12:22:39</LTime>
<FDate>2016-09-26</FDate>
<FTime>13:36:30</FTime>
<ReasonId>4</ReasonId>
<Flag>2</Flag>
</Details>
<Details>
<LoginId>1</LoginId>
<AId>1</AId>
<OId>765</OId>
<LDate>2016-09-26</LDate>
<LTime>10:22:39</LTime>
<FDate>2016-09-26</FDate>
<FTime>11:53:45</FTime>
<ReasonId>4</ReasonId>
<Flag>2</Flag>
</Details>
</tblTemp>
Based on LoginId I want to add child node in xml file.I have been trying code like this.
//code for adding child node
string strDBDir = "C:\\XMLfile.xml";
try
{
DataSet dsxml = new DataSet();
DataView DvXML = null;
dsxml.ReadXml(strDBDir);
DvXML = dsxml.Tables[0].DefaultView;
DvXML.RowFilter = "AId = '" + AId + "'";
if (File.Exists(strDBDir))
{
if (DvXML.ToTable().Rows.Count > 0)
{
LoginId = Convert.ToInt32(DvXML.ToTable().Rows[0]["LoginId"]);
XmlDocument originalXml = new XmlDocument();
originalXml.Load(strDBDir);
XmlNode TechReport = originalXml.SelectSingleNode("Details");
XmlNode Data = originalXml.CreateNode(XmlNodeType.Element, "FDate", null);
TechReport.AppendChild(Data);
originalXml.Save(strDBDir);
}
}
catch
{
}
For the above code i get an exception-"Object reference not set to an instance of an object"
Can you please guide on this,how to add the FDate and Ftime in DBfile.xml based on LoginId and AId.I have been struggling for this.
You can achieve that by changing your search.
Instead of the looking only for "Details" which will add the child elements randomly, use "Details[LoginId='4']"
XmlNode TechReport = originalXml.SelectSingleNode("Details[LoginId='4']");
Is this what you are looking for?
Also, I think you will need to use CreateElement instead of CreateNode
Using xml linq and changing all occurances
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication16
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement detail in doc.Descendants("Details"))
{
detail.Add(new object[] {
new XElement("LTime", DateTime.Now.ToString("hh:mm:ss")),
new XElement("FDate", DateTime.Now.Date.ToShortDateString())
});
}
}
}
}
you can try this way to adding a new child:
XmlDocument xml = new XmlDocument();
xml.Load(strDBDir);
XmlNodeList xnList = xml.SelectNodes("/tblTemp/Details");
foreach (XmlNode xn in xnList)
{
// here your **if** statement with check on loginId in **xn**
XElement child = new XElement("FDate");
child.SetValue("2016-09-26");
xn.AppendChild(child);
}
I think that
XmlNode TechReport = originalXml.SelectSingleNode("Details");
should be:
XmlNode TechReport = originalXml.SelectSingleNode("tblTemp/Details");
Or to be more precise:
XmlDocument originalXml = new XmlDocument();
originalXml.Load(strDBDir);
var TechReport = originalXml.SelectSingleNode($"tblTemp/Details[AId={AId}][LoginId={LoginId}]");
if (TechReport != null)
{
XmlNode Data = originalXml.CreateNode(XmlNodeType.Element, "FDate", null);
TechReport.AppendChild(Data);
originalXml.Save(strDBDir);
}
else
{
// Handle this as you see fit...
}
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");
}
}
}