Writing textbox values to xml file in C#.net - c#

I have two TextBoxes namely txtUserid and txtPassowrd.
I'm writing the values entered in textboxes to a XML file but I do not want the same txtuserid values to be written twice in XML - it should be overwritten.
For example :
If I enter in txtUserid=2 and txtPassword=I
and the second time if I enter txtUserid=2 and txtPassword=m
then I only want one entry to be kept in the XML file :
For the above example: the txtUserid=2 and textPassword=m
The code:
XDocument Xdoc = new XDocument(new XElement("Users"));
if (System.IO.File.Exists("D:\\Users.xml"))
{
Xdoc = XDocument.Load("D:\\Users.xml");
}
else
{
Xdoc = new XDocument();
}
XElement xml = new XElement("Users",
new XElement("User",
new XAttribute("UserId", txtUserName.Text),
new XAttribute("Password", txtPassword.Text)));
if (Xdoc.Descendants().Count() > 0)
{
Xdoc.Descendants().First().Add(xml);
}
else
{
Xdoc.Add(xml);
}
Xdoc.Save("D:\\Users.xml");

Search your existing XML document for a node where the UserId attribute matches your current one, and if it does, modify that one, else make a new one.
I'd imagine that your coude would resemble the following:
List<XElement> list = Xdoc.Descendants("User").Where(el => el.Attribute("UserId").Value == txtUserName.Text).ToList();
if (list.Count == 0)
{
// Add new node
}
else
{
// Modify the existing node
}
Edit: In response to your comment, the code to edit your XElement would look something like
string myValue = "myValue";
list.First().Attribute("ElementName").SetValue(myValue);

Writing textbox values to XML file in C#
protected void btnSave_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;
// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("Userid", Server.HtmlEncode(textUserid.Text));
myXmlElement.SetAttribute("Username", Server.HtmlEncode(textUsername.Text));
myXmlElement.SetAttribute("AccountNo", Server.HtmlEncode(txtAccountNo.Text));
myXmlElement.SetAttribute("BillAmount", Server.HtmlEncode(txtBillAmount.Text));
// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("InsertData.xml"));
// Re-bind data since the doc has been added to
BindData();
Response.Write(#"<script language='javascript'>alert('Record inserted Successfully Inside the XML File....')</script>");
textUserid.Text = "";
textUsername.Text = "";
txtAccountNo.Text = "";
txtBillAmount.Text = "";
}
void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
myXmlReader.Close();
}

Related

Adding customXML part to Word

I am trying to add a custom XML part to Word. What I am doing is I have generated an XML model that binds all my data in the Word file. This is how I am trying to fill it, but nothing is being added:
public void FeedCustomXmlParts(MyModel model, string xmlns)
{
var ser = new XmlSerializer(typeof(MyModel), xmlns);
using (var ms = new MemoryStream())
{
ser.Serialize(ms, model);
CustomXmlPart partLabel = GetCustomXmlPart(_wordDoc.MainDocumentPart, xmlns);
ms.Position = 0;
partLabel.FeedData(ms);
ms.Flush();
}
}
private static CustomXmlPart GetCustomXmlPart(MainDocumentPart mainDocumentPart, string targetNs)
{
if (mainDocumentPart == null)
{
throw new ArgumentNullException(nameof(mainDocumentPart));
}
return (from part in mainDocumentPart.CustomXmlParts
let xElement = part.GetXDocument().Root
where xElement != null
let ns = xElement.GetDefaultNamespace()
where ns == targetNs
select part).FirstOrDefault();
}
What am I doing wrong?
According to your description, I understand that you want to add custom XML parts to the word.
The following code example adds a custom XML part to a specified document.
private void AddCustomXmlPartToActiveDocument(Word.Document document)
{
string xmlString =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
"<employee>" +
"<name>Karina Leal</name>" +
"<hireDate>1999-04-01</hireDate>" +
"<title>Manager</title>" +
"</employee>" +
"</employees>";
Office.CustomXMLPart employeeXMLPart = document.CustomXMLParts.Add(xmlString, missing);
}
For more information, please refer to:To add a custom XML part to a Word document
Hope that helps!

C# append object to xml file using serialization

I am trying append a serialized object to an existing xml file beneath the root element, which I thought would be simple but is proving to be a little challenging.
The problem is in the AddShortcut method but I added some more code for completeness.
I believe what I need to do is:
load the file into an XmlDocument.
navigate to the node I want to append beneath (here the node name is Shortcuts).
create some type of writer and then serialize the object.
save the XmlDocument.
The trouble is in steps 2 and 3. I have tried different variations but I think using XPathNavigator somehow to find the "root" node to append under is a step in the right direction.
I have also looked at almost every question on Stack Overflow on the subject.
Any suggestions welcome. Here is my code
class XmlEngine
{
public string FullPath { get; set; } // the full path to the xmlDocument
private readonly XmlDocument xDoc;
public XmlEngine(string fullPath, string startElement, string[] rElements)
{
FullPath = fullPath;
xDoc = new XmlDocument();
CreateXmlFile(FullPath, startElement, rElements);
}
public void CreateXmlFile(string path, string startElement, string[] rElements)
{
try
{
if (!File.Exists(path))
{
// create a txt writer
XmlTextWriter wtr = new XmlTextWriter(path, System.Text.Encoding.UTF8);
// make sure the file is well formatted
wtr.Formatting = Formatting.Indented;
wtr.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
wtr.WriteStartElement(startElement);
wtr.Close();
// write the top level root elements
writeRootElements(path, rElements);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.WriteLine("Could not create file: " + path);
}
}
public void AddShortcut(Shortcut s)
{
xDoc.Load(FullPath);
rootNode = xDoc.AppendChild(xDoc.CreateElement("Shortcuts"));
var serializer = new XmlSerializer(s.GetType());
using (var writer = new StreamWriter(FullPath, true))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
serializer.Serialize(writer, s);
}
xDoc.Save(FullPath);
}
}
This code sample worked for me:
xml:
<?xml version="1.0" encoding="UTF-8"?>
<Launchpad>
<Shortcuts>
<Shortcut Id="1">
<Type>Folder</Type>
<FullPath>C:\SomePath</FullPath>
<Name>SomeFolderName</Name>
</Shortcut>
</Shortcuts>
</Launchpad>
Method:
public void AddShortcut(Shortcut s)
{
xDoc.Load(FullPath);
var rootNode = xDoc.GetElementsByTagName("Shortcuts")[0];
var nav = rootNode.CreateNavigator();
var emptyNamepsaces = new XmlSerializerNamespaces(new[] {
XmlQualifiedName.Empty
});
using (var writer = nav.AppendChild())
{
var serializer = new XmlSerializer(s.GetType());
writer.WriteWhitespace("");
serializer.Serialize(writer, s, emptyNamepsaces);
writer.Close();
}
xDoc.Save(FullPath);
}
load the file into an XmlDocument.
navigate to the node I want to append beneath (here the node name is Shortcuts).
create some type of writer and then serialize the object.
save the XmlDocument
So:
public void AddShortcut(Shortcut s)
{
// 1. load existing xml
xDoc.Load(FullPath);
// 2. create an XML node from object
XmlElement node = SerializeToXmlElement(s);
// 3. append that node to Shortcuts node under XML root
var shortcutsNode = xDoc.CreateElement("Shortcuts")
shortcutsNode.AppendChild(node);
xDoc.DocumentElement.AppendChild(shortcutsNode);
// 4. save changes
xDoc.Save(FullPath);
}
public static XmlElement SerializeToXmlElement(object o)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter writer = doc.CreateNavigator().AppendChild())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
}
return doc.DocumentElement;
}
This post

Can not read XML document containing ampersand symbol

I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example '&'.
I have to read the XML but I can not modify the document. How can I modify the Xml file using C#? My code so far:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc;
doc = new XmlDocument();
doc.Load("nuevo.xml");
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
textBox1.Text = nodo.InnerXml;
}
As #EBrown suggested, one possibility would be read the file content in a string variable and replace the & symbol with the correct representation for propert XML & and then parse the XML structure. A possible solution could look like this:
var xmlContent = File.ReadAllText(#"nuevo.xml");
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlContent.Replace("&", "&"));
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
}
The output is:
34 & 34
If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:
var xmlContent = File.ReadAllText(#"nuevo.xml");
var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
var edad = xmlDocument.Root.Element("edad").Value;
Console.WriteLine(edad);
The output is the same as above.

Incorrect parsing of Textbox in docx by OpenXML

I am reading a .docx file using OpenXML in C#. It reads everything correctly but strangely, the content of textbox is being read thrice. What could be wrong? Here is the code to read .docx:
public static string TextFromWord(String file)
{
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
StringBuilder textBuilder = new StringBuilder();
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file, false))
{
// Manage namespaces to perform XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("w", wordmlNamespace);
// Get the document part from the package.
// Load the XML in the document part into an XmlDocument instance.
XmlDocument xdoc = new XmlDocument(nt);
xdoc.Load(wdDoc.MainDocumentPart.GetStream());
XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
foreach (XmlNode paragraphNode in paragraphNodes)
{
XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager);
foreach (System.Xml.XmlNode textNode in textNodes)
{
textBuilder.Append(textNode.InnerText);
}
textBuilder.Append(Environment.NewLine);
}
}
return textBuilder.ToString();
}
The part of file I am talking about is:
The result is: I read it in a test application like this:
What's wrong here?

c# winforms Form Load ComboBox DropDownList get value from XML file

XML File:
<?xml version="1.0" encoding="utf-16"?>
<XMLFILE>
<Active>0</Active>
<Hits_Method>1</Hits_Method>
</XMLFILE>
What i'm trying to do is on Form1_Load get the value of ComboBox4 from XML File (Hits_Method) and when the program start to show me the value. i try something like this but didn't work out
// ------------------- StartUP Load
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlTextReader xreader = new XmlTextReader(xmlfile);
string comboBox4Value = xreader.GetAttribute("Hits_Method");
comboBox4.SelectedIndex = comboBox4Value;
}
Try this instead:
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);
string comboBox4Value = doc.SelectSingleNode("XMLFILE/Hits_Method").InnerText;
comboBox4.SelectedIndex = Convert.ToInt32(comboBox4Value);
}
The SelectSingleNode method extracts data based on an XPath expression. And "XMLFILE/Hits_Method" is the XPath that leads to your value.
I will use XmlDocument and XmlNode classes.
{
String sPath = "file.xml"
XmlDocument doc = new XmlDocument();
doc.Load(sPath)
XmlNode node = doc.SelectSingleNode("XMLFILE/Hits_Method");
if (node != null)
comboBox4.SelectedIndex = node.InnerText;
}

Categories