I'm having a little problem formatting my xml file using C# code in a Windows Form app. Here is the code i'm using for this project:
private void btnSend_Click(object sender, EventArgs e)
{
string _name = tbName.ToString();
string _st = tbSt.ToString();
string _dx = tbDx.ToString();
string _iq = tbIq.ToString();
string _filename = #"c:\Add.xml";
if (File.Exists(_filename))
{
XDocument xDoc = XDocument.Load(_filename);
xDoc.Root.Add(new XElement("character",
new XElement("name", _name),
new XElement("st", _st),
new XElement("dx", _dx),
new XElement("iq", _iq)
));
xDoc.Save(_filename);
}
else if (!File.Exists(_filename))
{
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("characters");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("character");
productsNode.AppendChild(productNode);
XmlNode nmNode = doc.CreateElement("name");
nmNode.AppendChild(doc.CreateTextNode(_name));
productNode.AppendChild(nmNode);
XmlNode stNode = doc.CreateElement("st");
stNode.AppendChild(doc.CreateTextNode(_st));
productNode.AppendChild(stNode);
XmlNode dxNode = doc.CreateElement("dx");
dxNode.AppendChild(doc.CreateTextNode(_dx));
productNode.AppendChild(dxNode);
XmlNode iqNode = doc.CreateElement("iq");
iqNode.AppendChild(doc.CreateTextNode(_iq));
productNode.AppendChild(iqNode);
doc.Save(#"c:\Add.xml");//must have to save
}
}
The problem is that my .xml file comes out with the whole TextBox class prefix attached such as this:
...
- <character>
<name>System.Windows.Forms.TextBox, Text: bob</name>
<st>System.Windows.Forms.TextBox, Text: 10</st>
<dx>System.Windows.Forms.TextBox, Text: 12</dx>
<iq>System.Windows.Forms.TextBox, Text: 08</iq>
</character>
I'd like to have it look like this:
- <character>
<name>bob</name>
<st>10</st>
<dx>12</dx>
<iq>08</iq>
</character>
If any of you fine knowledgeable folks could lend a hand (or point me a link) I'd appreciate it. I did comb through the Google but nothing turned up with this specific odd problem. Many thanks for any help you can offer.
The obvious I did not see. Thanks to those who may respond. Now that I post it, it is obvious.
Changing
string _name = tbName.ToString();
simply to
string _name = tbName.Text;
of course fixed the problem. Hope this may help someone else.
Related
I have an XML file that collects information with Button_Click, so it starts off empty.
XML Sample
<marina>
<dockone>
</dockone>
<docktwo>
</docktwo>
</marina>
When I submit information from a textbox, a new XmlNode is created called slipone, and another XmlNode called reg is nested within that.
XML Sample 2
<marina>
<dockone>
<slipone>
<reg>12345</reg>
<slipone>
</dockone>
<docktwo>
</docktwo>
</marina>
I have attempted to create an if/else statement that will add a new XmlNode called sliptwo, with reg still nested within it, if slipone already has text, like so:
<marina>
<dockone>
<slipone>
<reg>12345</reg>
<slipone>
<sliptwo>
<reg>67890</reg>
<sliptwo>
</dockone>
<docktwo>
</docktwo>
</marina>
However the closest I have gotten is another XMlnode is still created, however it labels itself as slipone, and I am not sure what I am doing wrong:
<marina>
<dockone>
<slipone>
<reg>12345</reg>
<slipone>
<slipone>
<reg>67890</reg>
<slipone>
</dockone>
<docktwo>
</docktwo>
</marina>
This is an example of what I have been playing around with. Ignore the operators as I have resorted to trial and error but still have gotten nowhere. Please help!
C# Example
XmlDocument XmlDocObj1 = new XmlDocument();
XmlDocObj1.Load(Server.MapPath("~/App_Data/SlipData.xml"));
XmlNode rootnode1 = XmlDocObj1.SelectSingleNode("marina/dockone");
XmlNode dockone = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "slipone", ""));
XmlNode docktwo = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "sliptwo", ""));
XmlNode dockthree = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "slipthree", ""));
if (regfinal.Text != dockone.InnerText)
{
dockone.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "Reg", "")).InnerText = regfinal.Text;
XmlDocObj1.Save(Server.MapPath("/App_Data/SlipData.xml"));
}
else if (regfinal.Text == dockone.InnerText)
{
docktwo.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "Reg", "")).InnerText = regfinal.Text;
XmlDocObj1.Save(Server.MapPath("/App_Data/SlipData.xml"));
}
Your logic isn't going to do what I think you are saying since the only time (regfinal.Text != dockone.InnerText) will evaluate to false is when you enter nothing in your text control.
I believe you might mean to say if dockone exists then create another node called docktwo. This will require you to change your logic.
Some very simple code to get you a bit farther down the path. Not intended to be perfect or solve all problems...
private void button1_Click(object sender, EventArgs e)
{
XmlDocument XmlDocObj1 = new XmlDocument();
XmlDocObj1.Load(AppDomain.CurrentDomain.BaseDirectory.ToString()+"test.xml");
XmlNode rootnode1 = XmlDocObj1.SelectSingleNode("marina/dockone");
XmlNode dockone = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "slipone", ""));
XmlNode docktwo = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "sliptwo", ""));
XmlNode dockthree = rootnode1.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "slipthree", ""));
//jsh: old logic
//if (textBox1.Text != dockone.InnerText)
//new logic to test whether we have already created the dockone node which should only occur once
//you already have the logic for selecting the dockone node above...now just test if you already have it.
//NOTE: you may actually want a switch statement given that you avhe dockone, docktwo, and dockthree or at least another
// if statement to see if docktwo has been created and thus creaste dockthree.
if (rootnode1 == null )
{
dockone.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "Reg", "")).InnerText = textBox1.Text;
XmlDocObj1.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.xml");
}
//else if (textBox1.Text == dockone.InnerText) jsh: old logic
else
{
docktwo.AppendChild(XmlDocObj1.CreateNode(XmlNodeType.Element, "Reg", "")).InnerText = textBox1.Text;
XmlDocObj1.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.xml");
}
}
I'm trying to update an existing XML file, but always when I update it adding new tags the xmlns="" attribute mysteriously appears in all tags and I didn't find a way to remove it.
private static void EditarXML(string path, List<SiteUrl> listaUrls, bool indice, string loc)
{
XmlDocument documentoXML = new XmlDocument();
documentoXML.Load(path);
XmlNode sitemap = documentoXML.CreateElement("sitemap");
XmlNode xloc = documentoXML.CreateElement("loc");
xloc.InnerText = loc;
sitemap.AppendChild(xloc);
XmlNode lastmod = documentoXML.CreateElement("lastmod");
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
documentoXML.DocumentElement.AppendChild(sitemap);
}
Any help or ideas would be appreciated.
This will happen with the parent node you are appending to has a namespace, but you don't specify it in the CreateElement() call.
To handle this, you can get the namespace from the DocumentElement, like this (my sample just creates the document in memory, but the principle is the same), and pass it to CreateElement().
if (x.DocumentElement != null) {
var xmlns = (x.DocumentElement.NamespaceURI);
var sitemap = x.CreateElement("sitemap", xmlns);
var xloc = x.CreateElement("loc", xmlns);
xloc.InnerText = "Hello";
sitemap.AppendChild(xloc);
var lastmod = x.CreateElement("lastmod", xmlns);
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
x.DocumentElement.AppendChild(sitemap);
}
Console.WriteLine(x.InnerXml);
Output
<test xmlns="jdphenix"><sitemap><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>
Note that if I did not pass the parent namespace to each CreateElement() call, the children of that call would have the blank xmlns.
// incorrect - appends xmlns=""
if (x.DocumentElement != null) {
var sitemap = x.CreateElement("sitemap");
var xloc = x.CreateElement("loc");
xloc.InnerText = "Hello";
sitemap.AppendChild(xloc);
var lastmod = x.CreateElement("lastmod");
lastmod.InnerText = DateTime.Now.ToShortDateString();
sitemap.AppendChild(lastmod);
x.DocumentElement.AppendChild(sitemap);
}
Console.WriteLine(x.InnerXml);
Output
<test xmlns="jdphenix"><sitemap xmlns=""><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>
Related reading: Why does .NET XML append an xlmns attribute to XmlElements I add to a document? Can I stop it?
How to prevent blank xmlns attributes in output from .NET's XmlDocument?
Is this possible to read or parse google map data(i-e http://www.ukairquality.net/MicrosoftMapFast2.aspx ) from external website
I just want to get data from this and store this data in my sql...
private void button1_Click(object sender, EventArgs e)
{
XmlDocument XmlDoc = new XmlDocument();
XmlNamespaceManager XmlNs = new XmlNamespaceManager(XmlDoc.NameTable);
XmlNs.AddNamespace("def", "http://earth.google.com/kml/2.0");
string url = "http://www.ukairquality.net/MicrosoftMapFast2.aspx ";
XmlDoc.Load(url);
//XmlDoc.Save(MapPath(#"~\xml\test.xml"));
XmlNodeList Nodes = XmlDoc.SelectNodes("//def:coordinates", XmlNs);
foreach (XmlNode Node in Nodes)
{
textBox1.Text= Response.Write(Node.InnerText + "<br />");
}
}
Sure you can load data from other webstes, but the URL you give is not XML. You'll get an error if you try to parse it as XML.
If you want to get the data from this UK site, then you'll need to look at their javascript and use string functions to get the parts you want.
I have the following code that works fine on my localhost using IIS7 but when i upload it to my server it is behaving not the same as it did on my localhost
For example the submit button when clicked should check validation which it does on my localhost and then redirects to a URL if the validation is correct
But when the same is tried on the actual server over here
The not working link
the problem started when i introduced a redirect url (in C# code is Response.Redirect("http://www.google.com");) in to the c# code...if there is a better way to do this all this hassle wont be necessary..tks
this is the code that i used
<%# Page Language="C#" Debug="true" %>
<%# Import Namespace="System.Xml" %>
<script runat="server">
protected void btnSave_Click(object sender, EventArgs e)
{
txtAddress.Text = "";
string xmlPath = MapPath("Books.xml");
XmlDocument doc = new XmlDocument();
//Check if the file already exists or not
if (System.IO.File.Exists(xmlPath))
{
doc.Load(xmlPath);
XmlNode bookNode = CreateBookNode(doc);
//Get reference to the book node and append the book node to it
XmlNode bookStoreNode = doc.SelectSingleNode("bookstore");
bookStoreNode.AppendChild(bookNode);
lblResult.Text = "XML Document has been successfully updated";
txtAddress.Text = ""; Response.Redirect("http://www.google.com");
}
else
{
XmlNode declarationNode = doc.CreateXmlDeclaration("1.0", "", "");
doc.AppendChild(declarationNode);
XmlNode comment = doc.CreateComment("This file represents a fragment of a book store inventory database");
doc.AppendChild(comment);
XmlNode bookstoreNode = doc.CreateElement("bookstore");
XmlNode bookNode = CreateBookNode(doc);
//Append the book node to the bookstore node
bookstoreNode.AppendChild(bookNode);
//Append the bookstore node to the document
doc.AppendChild(bookstoreNode);
lblResult.Text = "XML Document has been successfully created";
txtAddress.Text = "";Response.Redirect("http://www.google.com");
}
doc.Save(xmlPath);
}
XmlNode CreateBookNode(XmlDocument doc)
{
/*
XmlNode bookNode = doc.CreateElement("book");
//Add the genre attribute to the book node
XmlAttribute genreAttribute = doc.CreateAttribute("genre");
genreAttribute.Value = txtGenre.Text;
bookNode.Attributes.Append(genreAttribute);
http://www.java2s.com/Code/ASP/XML/SaveformdatatoXMLfile.htm
*/
XmlNode bookNode = doc.CreateElement("book");
//Declaration of the Main Node (Particulars)
XmlNode particularsnode = doc.CreateElement("Particulars");
//Declaration of Child Nodes in the Main Node(Particulars)
XmlNode nameNode = doc.CreateElement("Name");
XmlNode phoneNode = doc.CreateElement("Phone");
XmlNode emailNode = doc.CreateElement("Email");
XmlNode AddressNode = doc.CreateElement("Address");
//Getting the textvalue from the htmlform
nameNode.InnerText = txtName.Text;
phoneNode.InnerText = txtPhone.Text;
emailNode.InnerText = txtEmail.Text;
AddressNode.InnerText = txtAddress.Text;
//Updating the XML file here the particularsnode has various children and they are being updated
particularsnode.AppendChild(nameNode);
particularsnode.AppendChild(phoneNode);
particularsnode.AppendChild(emailNode);
particularsnode.AppendChild(AddressNode);
bookNode.AppendChild(particularsnode);
//Declaration of the Main Node (BookParticulars)
XmlNode bookparticularsnode = doc.CreateElement("BookParticulars");
//Declaration of Child Nodes in the Main Node(BookParticulars)
XmlNode schoolNode = doc.CreateElement("School");
XmlNode currentlevelNode = doc.CreateElement("CurrentLevel");
XmlNode GABDNode = doc.CreateElement("GiveAwayBookDetails");
XmlNode LRNode = doc.CreateElement("LevelRequired");
//Getting the textvalue from the htmlform
schoolNode.InnerText = txtSchool.Text;
currentlevelNode.InnerText = txtCurrentLevel.Text;
GABDNode.InnerText = txtGABD.Text;
LRNode.InnerText = txtLR.Text;
//Updating the XML file here the particularsnode has various children and they are being updated
particularsnode.AppendChild(schoolNode);
particularsnode.AppendChild(currentlevelNode);
particularsnode.AppendChild(GABDNode);
particularsnode.AppendChild(LRNode);
bookNode.AppendChild(bookparticularsnode);
return bookNode;
}
public static string NewLineToBreak(string input)
{
Regex regEx = new Regex(#"[\n|\r]+");
return regEx.Replace(input, "<br />");
}
protected void txtAddress_Load(object sender, EventArgs e)
{
txtAddress.Text = "Woodlands Drive 14\n Blk";
}
</script>
Try using Server.MapPath as describes in ASP.NET Web Project Paths or try using Page.ResolveUrl
Have you tried using fully qualified paths for the resources you're trying to load?
e.g.:
string xmlPath = MapPath("~/Books.xml");
-or-
string xmlPath = MapPath("~/<some_sub_dir>/Books.xml");
Also, is your production server throwing exceptions? If so, displaying them locally only and using a local http session to see them might help.
example web.config section for customerrors:
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
Try giving the fully qualified path and see if its picking the XML file. I am sure it might be some path issue that is causing the exception. Also make sure you turn on the Custom Errors mode so that you can see the error.
Im trying to use the ReplaceChild function. the code works, and no exceptions are thrown, but when I print XML to the screen it seems as if the function didnt work. the original node is the but not the new one.
private void convertClubComp(XmlDocument doc)
{
XmlNode sessionNode = doc.SelectSingleNode("Session");
XmlNode clubsNode = doc.CreateNode(XmlNodeType.Element, "Clubs", "");
XmlNode playerNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player");
XmlNode groupNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups");
Console.WriteLine(playerNode.Name);
clubsNode = doc.ImportNode(groupNode, true);
playerNode.ReplaceChild(clubsNode, sessionNode.SelectSingleNode("Players").SelectSingleNode("Player").SelectSingleNode("Groups"));
Console.WriteLine(clubsNode.FirstChild.FirstChild.Name);
Console.WriteLine("!"+playerNode.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.Name);
}
Thanks
Ok, what's happening is when you do the ImportNode() it is replacing your reference to the new node you created with a clone of the other node. I think what you're looking for is something along the lines of this:
private void convertClubComp(XmlDocument doc)
{
XmlNode sessionNode = doc.SelectSingleNode("Session");
XmlNode playerNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player");
XmlNode groupNode = playerNode.SelectSingleNode("Groups");
Console.WriteLine(playerNode.Name);
XmlNode clubsNode = doc.CreateElement("Clubs", "");
foreach (XmlNode child in groupNode.ChildNodes)
{
clubsNode.AppendChild(child.CloneNode(true));
}
foreach (XmlAttribute attribute in groupNode.Attributes)
{
clubsNode.Attributes.Append((attribute.Clone() as XmlAttribute));
}
playerNode.ReplaceChild(clubsNode, groupNode);
Console.WriteLine(clubsNode.FirstChild.FirstChild.Name);
Console.WriteLine("!" + playerNode.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.Name);
}
On a separate note, don't use SelectSingleNode() or SelectNodes() if you already have a reference. It's really poor practice and in larger systems can kill your performance.