writing to xml attributes - c#

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

Related

How to retrieve attribute from XML file in C#

I'm complete rookie I need to retrieve the value of last id in XML file here is
You can also use XPath within the Xml DOM like this :
string title;
XmlDocument xml = new XmlDocument();
xml.Load("~/purchases.xml");
// Or any other method to load your xml data in the XmlDocument.
// For example if your xml data are in a string, use the LoadXml method.
XmlElement elt = xml.SelectSingleNode("//SubMenu[#id='1']") as XmlElement;
if(elt!=null)
{
name=elt.GetAttribute("title");
}
Reference
As Jon suggested, you can use Linq To XML here.
XElement books = XElement.Load(filePath);
var lastId = books.Descendants("book").Select(x=>Int32.Parse(x.Attribute("ID").Value)).Last();
This will give you the last ID in the current list.You can now create your new Node
books.Add(new XElement("book",new XAttribute("ID",(lastId+1).ToString()),
new XAttribute("title","New Title"),
new XAttribute("price","1234")));
books.Save(filePath);
XmlDocument doc = new XmlDocument();
doc.Load("Yourxmlfilepath.xml");
//Display all the book titles.
XmlNodeList xNodeList = doc.SelectNodes("/bookstore/book");
foreach (XmlNode xNode in xNodeList)
{
var employeeName = xNode.OuterXml;
XmlDocument docnew = new XmlDocument();
docnew.LoadXml(employeeName);
foreach (XmlElement report in docnew.SelectNodes("book"))
{
string ID = report.GetAttribute("ID");
string title = report.GetAttribute("title");
string quantity = report.GetAttribute("quantity");
string price = report.GetAttribute("price");
}
}

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

Creating XMLDocument throguh code in asp.net

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

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

Replacing Whole XmlElement with new value

I have got below code in which I am taking html and then reading all the img and a links. Note this is C# 2.0.
string xml = "<xhtml>" + inputXhtml + "</xhtml>";
XmlDocument node = new XmlDocument();
node.LoadXml(xml);
foreach (XmlElement element in TemplateUtilities.SelectNodes(node, "//html:img[#xlink:href]|//html:a[#xlink:href]"))
{
bool flag = element.LocalName == "img";
lStrCompLinkText = "";
XmlAttributeCollection attributes = element.Attributes;
XmlAttribute namedItem = (XmlAttribute)attributes.GetNamedItem("href", "http://www.w3.org/1999/xlink");
string str2 = namedItem.Value;
Component currentObject = engine.GetObject(str2) as Component;
if (flag)
{
element.SetAttribute("src", str2);
}
else
{
foreach (XmlNode xnode in element.ChildNodes)
{
lStrCompLinkText = lStrCompLinkText + xnode.OuterXml;
}
string attr = ComponentBase.ComponentHelper.ComponentLinkAttributes(element, engine);
string compLink = ComponentBase.ComponentHelper.DisplayPublishedComponentLink(currentObject, lStrCompLinkText, attr, engine, package, pageObject);
attributes.RemoveNamedItem("href", "http://www.tridion.com/ContentManager/5.0");
//Here I want to replace whole element with the compLink
}
attributes.RemoveNamedItem("href", "http://www.w3.org/1999/xlink");
attributes.RemoveNamedItem("type", "http://www.w3.org/1999/xlink");
attributes.RemoveNamedItem("title", "http://www.w3.org/1999/xlink");
}
Now I want to replcace my element with the new value compLink and add back to the input HTML
Please suggest
At the spot where your comment "// Here I want to replace" appears do the following.
Create an XML Document from the contentes of compLink (assuming it's XML).
XmlDocument xmlTemp = new XmlDocument();
xmlTemp.loadXml( compLink );
Remove the original element from it's parent with the following code
XmlNode ndParent = element.ParentNode;
ndParent.RemoveChild( element);
Import and append the new xmlTemp to the parent
XmlNode ndImport = ndParent.OwnerDocument.ImportNode( xmlTemp.documentElement, true );
ndParent.AppendChild( ndImport.CloneNode( true ) );
I solved my above problem using below logic:
XmlDocument lObjTCDCodeDom = new XmlDocument();
lObjTCDCodeDom.LoadXml("<TCDCode/>");
lObjTCDCodeDom.DocumentElement.InnerText = compLink;
element.ParentNode.ReplaceChild(node.ImportNode(lObjTCDCodeDom.DocumentElement, true), element);
and then further wrote the XSLT which check the <TCDCode/> and replaces it and then I get actual updated xml.

Categories

Resources