Creating XMLDocument throguh code in asp.net - c#

am trying to generate an XML document like this through code.
<TestRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:2292/RMSchema.xsd">
<Version>3</Version>
<ApplicationHeader>
<AppLanguage />
<UserId>rmservice</UserId>
</ApplicationHeader>
<CustomerData>
<ExistingCustomerData>
<MTN>2084127182</MTN>
</ExistingCustomerData>
</CustomerData>
</TestRequest>
I tried some samples. But they create xmlns for the children, which i dont need. Any help is really appreciated.
I have tried the below code. But it is adding only xmlns to all children, which i dont need
XmlDocument xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
XmlElement xRoot = xDocument.CreateElement("TestRequest", "XNamespace.Xmlns=http://www.w3.org/2001/XMLSchema-instance" + " xsi:noNamespaceSchemaLocation=" + "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = 1;
Thanks
Tutu
I have tried with
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
XmlElement xRoot = xDocument.CreateElement("xsi","RMRequest",xsi);
xRoot.SetAttribute("noNamespaceSchemaLocation", xsi, "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
Now the response is
<?xml version=\"1.0\" encoding=\"windows-1252\"?><xsi:TestRequest xsi:noNamespaceSchemaLocation=\"http://localhost:2292/RMSchema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">

Here is the awesome LINQ to XML. Enjoy!
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(new XDeclaration("1.0", "windows-1252", null),
new XElement("TestRequest",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "noNamespaceSchemaLocation", "http://localhost:2292/RMSchema.xsd"),
new XElement("Version",
new XText("3")
),
new XElement("ApplicationHeader",
new XElement("AppLanguage"),
new XElement("UserId",
new XText("rmservice")
)
),
new XElement("CustomerData",
new XElement("ExistingCustomerData",
new XElement("MTN",
new XText("2084127182")
)
)
)
)
);
doc.Save(filePath);
If you really want the old API, here it is:
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
var attr = xDocument.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
EDIT: From your comments, it looks like you want the xmlns:xsi and other attribute in that specific order. If so, you may have to trick the XmlDocument to add the xmlns:xsi attribute first.
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
// add namespace decl are attribute
var attr = xDocument.CreateAttribute("xmlns:xsi");
attr.Value = xsi;
xRoot.Attributes.Append(attr);
// no need to specify prefix, XmlDocument will figure it now
attr = xDocument.CreateAttribute("noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);

Are you looking for something like this:-
XmlDocument xmldoc = new XmlDocument();
XmlNode root = xmldoc.AppendChild(xmldoc.CreateElement("Root"));
XmlNode child = root.AppendChild(xmldoc.CreateElement("Child"));
XmlAttribute childAtt =child.Attributes.Append(xmldoc.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "My node Innertext";
xmldoc.Save("ABC.xml");

Related

How to create xml nodes with colon

I want an xml output as under
<ExtendedData xmlns:section="http://svr:1245/contact/kml/section.xsd">
<section:secid>svr_01</section:secid>
<section:name>test</unit:name>
</ExtendedData>
How can I achieve this? My code is as below but the output is not correct
var attribute = xDoc.CreateAttribute("section","secid","http://svr:1245/contact/kml/section.xsd");
XmlElement elementExtendedData = xDoc.CreateElement("ExtendedData");
elementPlacemark.AppendChild(elementExtendedData);
var elementSectionid = xDoc.CreateElement("section", "secid");
attribute.InnerText = UniqueID;
elementSectionid.Attributes.Append(attribute);
elementExtendedData.AppendChild(elementSectionid);
First, create the ElementData element add add the namespace prefix xmlns:section. Then add your element with the correct prefix and namespace.
var extendedData = xDoc.CreateElement("ExtendedData");
extendedData.SetAttribute("xmlns:section", "http://svr:1245/contact/kml/section.xsd");
elementPlacemark.AppendChild(extendedData);
var secId = xDoc.CreateElement("section", "secid", "http://svr:1245/contact/kml/section.xsd");
secId.InnerText = "svr_01";
extendedData.AppendChild(secId);
If you have the option, I'd suggest using LINQ to XML instead, it's much nicer to work with:
XNamespace ns = "http://svr:1245/contact/kml/section.xsd";
var element = new XElement("ExtendedData",
new XAttribute(XNamespace.Xmlns + "section", ns),
new XElement(ns + "secid", "svr_01")
);
doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
XmlNode root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
string url2 = "http://www.w3.org/2000/09/xmldsig#"; //ds
XmlNode element1 = doc.CreateElement(NodoRaiz, "Facturae", "http://www.facturae.es/Facturae/2014/v3.2.1/Facturae");
XmlAttribute attr = doc.CreateAttribute("xmlns:ds");
attr.Value = url2;
element1.Attributes.Append(attr);
doc.AppendChild(element1);

How to update soap xml file element value in c#.net

How can I update the SOAP xml element value from an soap xml file using c#.net? My file is as below:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://extn.ssac.ee.sim.dsh.cms.hhs.gov/SsaCompositePortType/VerifySSAResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:27f0af81-0da7-441f-83a7-fb2beaf30664</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:e8dcd685-cb86-400a-8059-dcad985a7ea7</RelatesTo>
</soap:Header>
<soap:Body>
<exch:SSACompositeResponse xmlns:exch="http://ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:SSACompositeIndividualResponse xmlns:ssac="http://extn.ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:ResponseMetadata>
<ssac:ResponseCode>HS000000</ssac:ResponseCode>
<ssac:ResponseDescriptionText>Success</ssac:ResponseDescriptionText>
</ssac:ResponseMetadata>
<ssac:PersonSSNIdentification>199123051</ssac:PersonSSNIdentification>
<ssac:SSAResponse>
<ssac:SSNVerificationIndicator>true</ssac:SSNVerificationIndicator>
<ssac:DeathConfirmationCode>Unconfirmed</ssac:DeathConfirmationCode>
<nc:PersonUSCitizenIndicator xmlns:nc="http://niem.gov/niem/niem-core/2.0">true</nc:PersonUSCitizenIndicator>
<ssac:PersonIncarcerationInformationIndicator>false</ssac:PersonIncarcerationInformationIndicator>
<ssac:SSATitleIIAnnualIncomeInformationIndicator>false</ssac:SSATitleIIAnnualIncomeInformationIndicator>
<ssac:SSATitleIIMonthlyIncomeInformationIndicator>false</ssac:SSATitleIIMonthlyIncomeInformationIndicator>
<ssac:SSAQuartersOfCoverageInformationIndicator>false</ssac:SSAQuartersOfCoverageInformationIndicator>
</ssac:SSAResponse>
</ssac:SSACompositeIndividualResponse>
</exch:SSACompositeResponse>
Here I want to update ssac:PersonSSNIdentification (199123051) value to 9876543210?
XmlNamespaceManager xnm;
xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
XmlNodeList aNodes = xmlDoc.SelectNodes("/Envelope/Body/SSACompositeResponse/SSACompositeIndividualResponse");
foreach (XmlNode aNode in aNodes)
{ var innerXmlNode = aNode.SelectSingleNode("/PersonSSNIdentification");
if (innerXmlNode != null)
{ innerXmlNode.Value = lstSsn[0];
}
}
xmlDoc.Save(newSSAPathName);
But this doesn't work...is there any way...
I'd recommend doing this with LINQ to XML rather than the older XmlDocument API.
First, load your XML into an XDocument:
var doc = XDocument.Load(newSSAPathName);
Then, define an XNamespace for each of the namespaces you have in your XML:
var soap = (XNamespace)"http://www.w3.org/2003/05/soap-envelope";
var exch = (XNamespace)"http://ssac.ee.sim.dsh.cms.hhs.gov";
var ssac = (XNamespace)"http://extn.ssac.ee.sim.dsh.cms.hhs.gov";
Now query for all elements at the required depth in the XML hierarchy with the required fully qualified names:
var ssnIds = doc.Elements(soap + "Envelope")
.Elements(soap + "Body")
.Elements(exch + "SSACompositeResponse")
.Elements(ssac + "SSACompositeIndividualResponse")
.Elements(ssac + "PersonSSNIdentification");
Finally, change the appropriate element value:
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
Alternatively, if you do want to use an XPATH query, you need to populate an XmlNamespaceManager with all 3 namespaces. The documentation for XPathSelectElements(XNode, String, IXmlNamespaceResolver) shows how to do this. Then use the prefixes you chose corresponding to each namespace in your XPATH query:
using (var reader = XmlReader.Create(newSSAPathName))
{
var doc = XDocument.Load(reader);
// Set up a namespaceManager as described in https://msdn.microsoft.com/en-us/library/bb351355%28v=vs.110%29.aspx
var nameTable = reader.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = doc.XPathSelectElements("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
}
Be sure to do using System.Xml.XPath; at the beginning of the file since XPathSelectElements is an extension method.
Update
Using XmlDocument, the equivalent XPATH query is:
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
var nameTable = xmlDoc.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = xmlDoc.SelectNodes("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (XmlNode ssnId in ssnIds)
if (ssnId.InnerText == "199123051")
ssnId.InnerText = "9876543210";

Writing Xml in Windows Phone Application

I have this code that work fine to create an xml document for my WPF application.
var doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
var parentNode = doc.CreateElement("manga");
doc.AppendChild(parentNode);
foreach (var mList in mangaList)
{
var itemNode = doc.CreateElement("item");
var itemAttribute = doc.CreateAttribute("value");
itemAttribute.Value = mList.Key;
itemNode.InnerText = mList.Value;
itemNode.Attributes.Append(itemAttribute);
parentNode.AppendChild(itemNode);
}
var writer = new XmlTextWriter(#"Data\mangalist.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
Now I want to create similar application for Windows Phone 7.5 and i'm stuck in porting above code to be able to run in WP. After quick searching i found that XmlDocument is not available in Windows Phone and have to switch using XDocument. I am far from familiar with XDocument and hope somebody can help to me make my windows phone apps outputting the same xml.
Thanks
Solution :
After good hints from #Pradeep Kesharwani and #dav_i I managed to port those codes above to use XDocument and StreamWriter instead of XmlDocument and XmlTextWriter which are not available for WP:
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
var root = new XElement("manga");
var mangaList = new Dictionary<string, string>();
mangaList.Add("conan", "conan");
mangaList.Add("naruto", "naruto");
foreach (var mList in mangaList)
{
var itemNode = new XElement("item");
var itemAttribute = new XAttribute("value", mList.Key);
itemNode.Value = mList.Value;
itemNode.Add(itemAttribute);
root.Add(itemNode);
}
doc.Add(root);
using (var writer = new StreamWriter(#"Data\mangalist2.xml"))
{
writer.Write(doc.ToString());
}
As I said in comments, XDocument is pretty straight forward -
new XDocument(
new XDeclaration("1.0", "utf-8", "no"),
new XElement("root",
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
),
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
)
)
)
Gives the following
<root>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
</root>
Hopefully this will help you!
To automatically populate in a loop, you could do something like this:
var somethings = new List<XElement>();
for (int i = 0; i < 3; i++)
somethings.Add(new XElement("something", new XAttribute("attribute", i + 1)));
var document = new XDocument(
new XElement("root",
somethings));
Which results in
<root>
<something attribute="1" />
<something attribute="2" />
<something attribute="3" />
</root>
This Create method could be used to create a xml doc in wp7
private void CreateXml()
{
string xmlStr = "<RootNode></RootNode>";
XDocument document = XDocument.Parse(xmlStr);
XElement ex = new XElement(new XElement("FirstNOde"));
XElement ex1 = new XElement(new XElement("second"));
ex1.Value = "fdfgf";
ex.Add(ex1);
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(ex);
string newXmlStr = document.ToString();
}
This will be the created xml
<RootNode>
<ChildNode>World!</ChildNode>
<ChildNode>World!</ChildNode>
<FirstNOde>
<second>fdfgf</second>
</FirstNOde>
</RootNode>
public void ReadXml()
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Your xml file name", FileMode.Open);
using (XmlReader reader = XmlReader.Create(isoFileStream))
{
XDocument xml = XDocument.Load(reader);
XElement root1 = xml.Root;
}
}

How to insert xml data into existing xml in c#?

i added xml file in my windows application, i want to add values to that from textbox..
i used the following code,
string path = "codedata.xml";
XmlDocument doc = new XmlDocument();
if (!System.IO.File.Exists(path))
{
//Create neccessary nodes
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
}
else //If there is already a file
{
// //Load the XML File
doc.Load(path);
}
//Get the root element
XmlElement root = doc.DocumentElement;
XmlElement Subroot = doc.CreateElement("data");
XmlElement Companycode = doc.CreateElement("Companycode");
XmlElement Productcode = doc.CreateElement("Productcode");
XmlElement Productname = doc.CreateElement("Productname");
XmlElement Brandcode = doc.CreateElement("Brandcode");
XmlElement Brandname = doc.CreateElement("Brandname");
Companycode.InnerText = txt_companycode.Text;
Productcode.InnerText = txt_productcode.Text;
Productname.InnerText = txt_productname.Text;
Brandcode.InnerText = txt_brandcode.Text;
Brandname.InnerText = txt_brandname.Text;
Subroot.AppendChild(Companycode);
Subroot.AppendChild(Productcode);
Subroot.AppendChild(Productname);
Subroot.AppendChild(Brandcode);
Subroot.AppendChild(Brandname);
root.AppendChild(Subroot);
doc.AppendChild(root);
//Save the document
doc.Save(path);
//Show confirmation message
MessageBox.Show("Details added Successfully");
it showing error near root.AppendChild(Subroot); can any one help me, wer i made mistake.
You can use Linq to XML, here is an example :
var xDoc = XElement.Load("FilePath");
if (xDoc == null)
return;
var myNewElement = new XElement("ElementName"
new XAttribute("AttributeName", value1),
new XAttribute("AttributeName", value2)
//And so on ...
);
xDoc.Add(myNewElement);
xDoc.Save("FilePath");
The root is null. Try to add Root element when you create XML file.
if (!System.IO.File.Exists(path))
{
//Create neccessary nodes
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(doc.CreateElement("Root"));
}
Or use LINQ-XML
string _file=#"c:\sample.xml";
XDocument doc;
if (!File.Exists(_file))
{
doc = new XDocument();
doc.Add(new XElement("Root"));
}
else
{
doc = XDocument.Load(_file);
}
doc.Root.Add(
new XElement("data",
new XElement("CompanyCode","C101"),
new XElement("ProductCode","P101")
)
);
doc.Save(_file);
In null XML DocumentElement is null. Try add Subroot to Document:
XmlElement root = doc.DocumentElement;
root.AppendChild(Subroot);
doc.AppendChild(root);
// new code
doc.AppendChild(Subroot);

writing to xml attributes

Hey all i have code to write to an xml doc from asp
string filePath = Server.MapPath("../XML/MyXmlDoc.xml");
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filePath);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
string startElement = "markings";
xmlWriter.WriteStartElement(startElement);
xmlWriter.Close();
xmlDoc.Load(filePath);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement mainNode = xmlDoc.CreateElement("mark");
XmlElement childNode1 = xmlDoc.CreateElement("studentFirstName");
XmlElement childNode2 = xmlDoc.CreateElement("studentLastName");
XmlElement childNode3 = xmlDoc.CreateElement("className");
XmlElement childNode4 = xmlDoc.CreateElement("marks");
XmlText childTextNode1 = xmlDoc.CreateTextNode("");
XmlText childTextNode2 = xmlDoc.CreateTextNode("");
XmlText childTextNode3 = xmlDoc.CreateTextNode("");
XmlText childTextNode4 = xmlDoc.CreateTextNode("");
root.AppendChild(mainNode);
//this portion can be added to a foreach loop if you need to add multiple records
childTextNode1.Value = "John";
childTextNode2.Value = "Doe";
childTextNode3.Value = "Biology";
childTextNode4.Value = "99%";
mainNode.AppendChild(childNode1);
childNode1.AppendChild(childTextNode1);
mainNode.AppendChild(childNode2);
childNode2.AppendChild(childTextNode2);
mainNode.AppendChild(childNode3);
childNode3.AppendChild(childTextNode3);
mainNode.AppendChild(childNode4);
childNode4.AppendChild(childTextNode4);
//end of loop section
xmlDoc.Save(filePath);
which works fine but i want to store the xml in the following structure
graph
set name="John Doe" value="99";
/graph
instead of
name John Doe /name
value 99 /value
is there a way to store the xml like this? thanks all
You can add an attribute to your XmlElement by using the following syntax (C#) :
XmlAttribute value = xmlDoc.CreateAttribute("value");
childNode1.attributes.appendChild(value);
Hope this helps !
This code will do what you're looking for:
XmlElement graph = xmlDoc.CreateElement("graph");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = "John Doe";
XmlAttribute value = xmlDoc.CreateAttribute("value");
value.Value = "99";
graph.SetAttributeNode(name);
graph.SetAttributeNode(value);
mainNode.AppendChild(graph);

Categories

Resources