Hi I am working on XML file, here I want to give rights to user to edit my xml file nodes to his own custom language.
I am enclosing my code, but it is not editting my xml file. Need assistance.
class Program
{
static void Main(string[] args)
{
//The Path to the xml file
string path = "D://Documents and Settings//Umaid//My Documents//Visual Studio 2008//Projects//EditXML//EditXML//testing.xml";
//Create FileStream fs
System.IO.FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Create new XmlDocument
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
//Load the contents of the filestream into the XmlDocument (xmldoc)
xmldoc.Load(fs);
//close the fs filestream
fs.Close();
//Change the contents of the attribute
xmldoc.DocumentElement.ChildNodes[0].Attributes[0].InnerText = "Umaid";
// Create the filestream for saving
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
// Save the xmldocument
xmldoc.Save(WRITER);
//Close the writer filestream
WRITER.Close();
}
}
My XML file which I am going to edit, but couldn't.
<?xml version="1.0" encoding="utf-8" ?>
<rule id="city" scope="public">
<one-of>
<item>Boston</item>
</one-of>
</rule>
What do you really want to do with your XML?? Which attribute to you want to change??
One hint: you can load and save XmlDocument to a path directly - no need for the filestream .....
xmldoc.Load(#"D:\yourpath\file.xml");
xmldoc.Save(#"D:\yourpath\newfile.xml");
The problem is that your expression xmldoc.DocumentElement.ChildNodes[0] selects the <one-of> node which has no attributes.
You cannot change a non-existing attribute.
If you want to change the "id" attribute of <rule>, you need to do this on the DocumentElement:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
If you want to change the text inside the <item>, do this:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
Marc
class Program
{
static void Main(string[] args)
{
string path = "D:\\Documents and Settings\\Umaid\\My Documents\\Visual Studio 2008\\Projects\\EditXML\\EditXML\\testing.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
var itemNode = doc.SelectSingleNode("rule/one-of/item");
if (itemNode != null)
{
itemNode.InnerText = "Umaid";
}
doc.Save(path);
}
}
Related
**
I want to add XML schema and XML element together in same file. Because this xml file we will need to generate through C# based on specific record. So, i am looking some code help how can i write together XMLSchema and XML element in same file and inside same element. Please check attachment.
<Survey>
**Here i want XML schema**
**Here i want XML element**
</Survey>
Working Code Example
SiteSurveyX siteSurveyX = new SiteSurveyX();
XmlTextReader reader = new XmlTextReader("c:\\temp\\TestSiteSchema.xsd");
//siteSurveyX.SurveySchema = XmlSchema.Read(reader, null);
XmlSchema myschema = XmlSchema.Read(reader, null);
string filePath = HelperFunctions.SurveyFilePath + routeName;
////Get all node record from DB
siteSurveyX.Survey = routeService.GetRouteDetailForXML(routeId, Convert.ToString(ddlRoute.Text), chkCurrentInterruption.Checked);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
lblStatus.Text = "Preparing file";
stream.Close();
stream.Dispose();
//Convert record in XML
XmlSerializer serializer = new XmlSerializer(typeof(SiteSurveyX));
using (StreamWriter writer = new StreamWriter(filePath, true))
{
serializer.Serialize(writer, siteSurveyX);
lblStatus.Text = "Ready";
}
}
It's done with this code.
My program is a HTML parser and it saves everything into XML file. The problem is when I'm trying open a file and read the text, it gives me for example:"NAME"
when it should be "NAME"
It seems that when I use .Replace(""", """) It writes " as & ; quot ; once again. How should I handle it?
Edit:
It's <td> "IN QUOTE" BLA BLA BLA</td>
I do save this right here:
debt.Debtor.LegalPerson.Name = nazwa;
While debuging, the string I get is: "IN QUOTE" BLA BLA BLA
But when I write everything into XML
var serializer = new XmlSerializer(typeof(BGW_IMPORT));
serializer.Serialize(writer, bgw);
}
...
}
if (File.Exists(FilePath))
{
//XDocument existing;
XmlDocument ex = new XmlDocument();
XmlDocument docX = new XmlDocument();
using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
//existing = XDocument.Load(fs);
docX.LoadXml(doc.Document.ToString());
ex.Load(fs);
foreach (XmlNode wiersz in docX.SelectNodes("//Debt"))
{
XmlNode importNode = ex.ImportNode(wiersz, true);
ex.DocumentElement["Debts"].AppendChild(importNode);
}
}
File.Delete(FilePath);
using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
ex.Save(fs);
}...
At the end I get:
<Name>"IN QUOTE"BLA BLA BLA</Name>
When I want a:
<Name>"IN QUOTE"BLA BLA BLA</Name>
you first need to encode your string using
System.Web.HttpUtility.HtmlEncode ()
and then decode using HtmlDecode()
refer to the link: https://msdn.microsoft.com/en-us/library/7c5fyk1k(v=vs.110).aspx
I am using the savefiledialog in C# and I am allowing the user to save an xml node to a file however if the user chooses to create a new file and save the node in it, it works but when the user chooses to save to an existing file then it is overwritten. what I need is that it kind of loads the file and I can append the node in it, Thanks
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.FileName = "untitled"; // Default file name
sfd.DefaultExt = ".xml"; // Default file extension
sfd.Filter = "Xml documents (.xml)|*.xml";
Nullable<bool> result = sfd.ShowDialog();
if (result == true)
{
if (System.IO.Path.GetExtension(sfd.FileName) != ".xml")
{
MessageBox.Show("You can only choose files with .xml extensions");
return;
}
this.save_xml_file(sfd.FileName);
}
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
doc.AppendChild(docNode);
XmlNode fubiRec = Doc.CreateElement("FubiRecognizers");
XmlAttribute conf = Doc.CreateAttribute("globalMinConfidence");
conf.Value = "0.51";
fubiRec.Attributes.Append(conf);
doc.AppendChild(fubiRec);
XmlAttribute gestureAttribute = doc.CreateAttribute("name");
gestureAttribute.Value = gestureName;
gestureNode.Attributes.Append(gestureAttribute);
fubiRec.AppendChild(gestureNode);
If you use FileStream and StreamWriter then you need to specify your type of Stream first.
FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write);
FileMode.Append will create file if it doesn't exist,and append the one that exists.
Then use it in StreamWriter
StreamWriter sw = new StreamWriter(fileSTream, Encoding.Default);
If you don't use this kind of stream or writer, there is always something similar available.
I want to extract a xlsx file to get the sheet1.xml file. Now I am struggling with the package and PackagePart. I think the most obvious way is to read that particular file and copy the content to the XmlDocument
This is what i have this far:
XmlDocument doc = new XmlDocument();
using (Package package = ZipPackage.Open(xlsFile, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
{
FileStream targetFile = File.OpenWrite(target);
byte[] bytes = new byte[source.Length];
source.Read(bytes, 0, (int)source.Length);
source.Close();
//source.CopyTo(targetFile);
//doc.Load(source.Write());
//targetFile.Close();
}
}
}
I am using .net 3,5 so I cannot use the Stream source.CopyTo methods.
I would like to copy the contents of the Sheet1.xml to the doc of the XmlDocument class..
Thanks!
Paul
You can use XmlDocument.Load overload which takes a Stream:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
Once loaded, you then can use XmlDocument.Save:
xmlDoc.Save(target);
I've already written code to parse my xml file with an XmlReader so I don't want to rewrite it. I've now added encryption to the program. I have encrypt() and decrypt() functions which take an xml document and the encryption algorithm. I have a function that uses an xml reader to parse the file but now with the xml document I'm not sure how to create the xmlreader.
The question is how to save my xml document to a stream. I'm sure it's simple but I don't know anything about streams.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filep);
Decrypt(doc, key);
Stream tempStream = null;
doc.Save(tempStream); // <--- the problem is here I think
using (XmlReader reader = XmlReader.Create(tempStream))
{
while (reader.Read())
{ parsing code....... } }
You can try with MemoryStream class
XmlDocument xmlDoc = new XmlDocument( );
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );
xmlStream.Flush();//Adjust this if you want read your data
xmlStream.Position = 0;
//Define here your reading
Writing to a file:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<FTPSessionOptionInfo><HostName>ftp.badboymedia.ca</HostName></FTPSessionOptionInfo>");
using (StreamWriter fs = new StreamWriter("test.xml"))
{
fs.Write(doc.InnerXml);
}
}
I realize this is an old question, but thought it worth adding a method from this nice little blog post. This edges out some less performant methods.
private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
return XDocument.Load(new XmlNodeReader(doc));
}
try this
XmlDocument document= new XmlDocument( );
string pathTmp = "d:\somepath";
using( FileStream fs = new FileStream( pathTmp, FileMode.CreateNew ))
{
document.Save(pathTmp);
fs.Flush();
}