How to add attribute value in xml - c#

i use this code for creating xml file using c# class.
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode RootNode = doc.CreateElement("SDF");
doc.AppendChild(RootNode);
XmlAttribute rootAttribute2 = doc.CreateAttribute("Version");
rootAttribute2.Value = "3.0";
RootNode.Attributes.Append(rootAttribute2);
XmlAttribute rootAttribute = doc.CreateAttribute("xmlns:sdf");
rootAttribute.Value = "http://www.w3.org/2001/XMLSchema-instance";
RootNode.Attributes.Append(rootAttribute);
XmlAttribute rootAttribute1 = doc.CreateAttribute("sdf:noNamespaceSchemaLocation");
rootAttribute1.Value = "SDF.xsd";
RootNode.Attributes.Append(rootAttribute1);
output of this code..
<?xml version="1.0" encoding="UTF-8"?>
<SDF Version="3.0" xmlns:sdf="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="SDF.xsd">
but i want output like that
<?xml version="1.0" encoding="UTF-8"?>
<SDF Version="3.0" xmlns:sdf="http://www.w3.org/2001/XMLSchema-instance" sdf:noNamespaceSchemaLocation="SDF.xsd">

You need to use a different overload:
XmlAttribute rootAttribute1 =
doc.CreateAttribute("sdf", "noNamespaceSchemaLocation", null);

Use Overloaded version CreateAttribute method.
doc.CreateAttribute("name","namespaceURI")
See below link for detials.
http://msdn.microsoft.com/en-us/library/System.Xml.XmlDocument.CreateAttribute%28v=vs.110%29.aspx

i searched on google and find answer that solve my problem
XmlNode RootNode = doc.CreateElement("SDF");
doc.AppendChild(RootNode);
XmlAttribute rootAttribute2 = doc.CreateAttribute("Version");
rootAttribute2.Value = "3.0";
RootNode.Attributes.Append(rootAttribute2);
XmlAttribute newAttr = doc.CreateAttribute("sdf", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
newAttr.Value = "SDF.xsd";
RootNode.Attributes.Append(newAttr);

Related

XML formatting comes out wrong

I am trying to make an XML document through C# with a specific format, but I am having trouble getting it to look right. Here is what it comes out as:
<?xml version="1.0" encoding="UTF-8" ?>
<loanRequest d1p1:ssn=""
d1p2:creditScore=""
d1p3:loanAmount=""
d1p4:loanDuration=""
xmlns:d1p4="26-08-2015 12:41:11"
xmlns:d1p3="147862"
xmlns:d1p2="266"
xmlns:d1p1="765383-2478" />
Here is what it should have been:
<?xml version="1.0" encoding="UTF-8" ?>
<LoanRequest>
<ssn>765383-2478</ssn>
<creditScore>266</creditScore>
<loanAmount>147862</loanAmount>
<loanDuration>2015-08-26 12:41:11.0 CET</loanDuration>
</LoanRequest>
XML manipulation in C# is really confusing to me and I have a hard time piecing together how to do it. The code that I use to make the XML document is as follows:
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode loanRequest = doc.CreateElement("loanRequest");
XmlAttribute ssn = doc.CreateAttribute("ssn", l.SSN);
XmlAttribute creditscore = doc.CreateAttribute("creditScore", ""+l.CreditScore);
XmlAttribute loanamount = doc.CreateAttribute("loanAmount", ""+l.LoanAmount);
XmlAttribute loanduration = doc.CreateAttribute("loanDuration", l.LoanDuration.ToString());
loanRequest.Attributes.Append(ssn);
loanRequest.Attributes.Append(creditscore);
loanRequest.Attributes.Append(loanamount);
loanRequest.Attributes.Append(loanduration);
doc.AppendChild(loanRequest);
Why not use Linq to Xml
XDocument doc = new XDocument(
new XComment("this is a comment"),
new XElement("LoanRequest",
new XElement("ssn", l.SSN),
new XElement("creditScore", l.CreditScore),
new XElement("loanAmount", l.LoanAmount),
new XElement("loanDuration", l.loanDuration.ToString())));
doc.Save(path);
Apparently you add as attributes what should be nodes. Replace the calls of CreateAttribute with calls of AppendChild.

C# how to create a custom xml document

I'm really just trying to create a custom xml document for simple configuration processing.
XmlDocument xDoc = new XmlDocument();
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
What i'm trying to get is this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
i get not set to value of an object at xDoc.DocumentElement.AppendChild(xmlNode);
Unfortunately, You can't make that XML structure.
All XML documents must have a single root node. You can't have more.
Try something like this
XmlDocument xDoc = new XmlDocument();
xDoc.AppendChild( xDoc.CreateElement("root"));
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
It is not possible to have that XML structure as XML MUST have a single root element. You may want to try:
<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
</items>

Reading attribute of an XML file

I have this XML file, I can read all the the nodes
<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
<CTe xmlns="http://www.portalfiscal.inf.br/cte">
<infCte versao="1.04" ID="CTe3512110414557000014604"></infCte>
</CTe>
</cteProc>
I have tried reading this using C#
string chavecte;
string CaminhoDoArquivo = #"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
chavecte = xmlDoc.SelectSingleNode("infCTe")
.Attributes.GetNamedItem("Id").ToString();
but something is wrong with this code.
If you want to use Linq To Xml
var xDoc = XDocument.Load(CaminhoDoArquivo);
XNamespace ns = "http://www.portalfiscal.inf.br/cte";
var chavecte = xDoc.Descendants(ns+"infCte").First().Attribute("id").Value;
PS: I am assuming your xml's invalid line is as
<infCte versao="1.04" id="CTe3512110414557000014604"></infCte>
replace
chavecte = xmlDoc.SelectSingleNode("infCTe").Attributes.GetNamedItem("Id").Value;
with
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ab", "http://www.portalfiscal.inf.br/cte");
chavecte = xmlDoc.SelectSingleNode("//ab:infCte", nsmgr)
.Attributes.GetNamedItem("Id").Value;
I've also noticed that infCte doesn't have the ID attribute properly defined in your xml
Another possible solution is:
string CaminhoDoArquivo = #"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
// Select the node you're interested in
XmlNode node = xmlDoc.SelectSingleNode("/cteProc/CTe/infCte");
// Read the value of the attribute "ID" of that node
string chavecte = node.Attributes["ID"].Value;

Whats wrong with my XPath?

I try to parse this XML file (config file from Chirpy):
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="urn:ChirpyConfig"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ChirpyConfig http://www.weirdlover.com/chirpy/chirp.xsd">
<FileGroup Name="Built.debug.js" Minify="false">
<File Path="jquery/jquery-1.7.2.js"/>
<File Path="jquery.address/jquery.address-1.4.js" />
</FileGroup>
</root>
with this code:
var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config");
var file = new XPathDocument(path);
var nav = file.CreateNavigator();
var nodes = nav.Select("/root/FileGroup/File");
but nodes is always empty, regardless of how I call the nav.Select method. I barely used XPath before so maybe I'm doing it wrong - but what? Only the selector * gives me the root node.
What would be the selector to get the Path Attribute of all File nodes?
EDIT: SOLUTION
Thanks to Kirill, the final solution looks like this:
var path = Server.MapPath("~/Scripts/ScriptfilesMashup.chirp.config");
var file = new XPathDocument(path);
var nav = file.CreateNavigator();
var ns = "urn:ChirpyConfig";
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", ns);
var nodes = nav.Select("/x:root/x:FileGroup/x:File/#Path", nsMgr);
while(nodes.MoveNext())
{
var path = nodes.Current.Value;
}
It is because elements root, FileGroup and File are defined in urn:ChirpyConfig namespace.
Use this:
XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", "urn:ChirpyConfig");
XPathNavigator result = nav.SelectSingleNode("/x:root/x:FileGroup/x:File", nsMgr);

How to add attributes to xml using XmlDocument in c# .net CF 3.5

I need to create an attribute "abc" with the prefix "xx" for an element "aaa". The following code adds the prefix but it also adds the namespaceUri to the element.
Required Output:
<mybody>
<aaa xx:abc="ddd"/>
<mybody/>
My Code:
XmlNode node = doc.SelectSingleNode("//mybody");
XmlElement ele = doc.CreateElement("aaa");
XmlAttribute newAttribute = doc.CreateAttribute("xx","abc",namespace);
newAttribute.Value = "ddd";
ele.Attributes.Append(newAttribute);
node.InsertBefore(ele, node.LastChild);
The above code generates :
<mybody>
<aaa xx:abc="ddd" xmlns:xx="http://www.w3.org/1999/XSL/Transform"/>
<mybody/>
Desired output is
<mybody>
<aaa xx:abc="ddd"/>
<mybody/>
And the declaration of the "xx" attribute should be done in the root node like :
<ns:somexml xx:xsi="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://x.y.z.com/Protocol/v1.0">
How can if get the output in the deisred format? If the xml is not in this desired format then it cannot be processed anymore..
Can anyone help?
Thanks,
Vicky
I believe it's just a matter of setting the relevant attribute directly on the root node. Here's a sample program:
using System;
using System.Globalization;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
string ns = "http://sample/namespace";
XmlAttribute nsAttribute = doc.CreateAttribute("xmlns", "xx",
"http://www.w3.org/2000/xmlns/");
nsAttribute.Value = ns;
root.Attributes.Append(nsAttribute);
doc.AppendChild(root);
XmlElement child = doc.CreateElement("child");
root.AppendChild(child);
XmlAttribute newAttribute = doc.CreateAttribute("xx","abc", ns);
newAttribute.Value = "ddd";
child.Attributes.Append(newAttribute);
doc.Save(Console.Out);
}
}
Output:
<?xml version="1.0" encoding="ibm850"?>
<root xmlns:xx="http://sample/namespace">
<child xx:abc="ddd" />
</root>

Categories