Xml File should create new line and leave the previous data - c#

How can I write an XML file so that it starts a new line and does not overwrite the previous data?
string pfad = "C:\\temp\\Accounts.xml";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Login");
XmlElement id = doc.CreateElement("user");
XmlElement username = doc.CreateElement("username");
username.InnerText = txtBenutzerName.Text;
id.AppendChild(username);
root.AppendChild(id);
doc.AppendChild(root);
doc.Save(pfad);
MessageBox.Show("Created SuccesFully!");

Instead of creating a new document by this line
XmlDocument doc = new XmlDocument();
you should load existing file like this:
XmlDocument doc = new XmlDocument();
doc.Load(pfad);
...below code is the same...

XmlDocument doc = new XmlDocument();
doc.Load("C:\\Accounts.xml");
doc.GetElementsByTagName("username")[0].InnerText="sdkjfsdknfkds";
doc.Save("C:\\Accounts.xml");

Related

how do we deal with not knowing the prefix/namespace?

How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?
I'm parsing XML like so :
var doc = new XmlDocument();
doc.LoadXml(input);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace(nsPrefix, ns);
var nodes = doc.SelectNodes(xpath, nsmgr);
This works totally fine when the nsPrefix as well as the ns are passed in and non-empty.
However, when the namespace/prefix are empty for example in this scenario:
Then I am unable to correctly parse the XML.
The full function is:
public static class XPathWalker
{
public static IEnumerable<string> GetListOfAttachments(string input, string xpath, string nsPrefix, string ns)
{
var doc = new XmlDocument();
doc.LoadXml(input);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace(nsPrefix, ns);
var nodes = doc.SelectNodes(xpath, nsmgr);
foreach (XmlNode node in nodes)
{
if (string.IsNullOrWhiteSpace(node.InnerText))
{
continue;
}
yield return node.InnerText;
}
}
}
How do I iterate through a specific xpath against an XmlDocument that has no prefix/namespace ?
There was indeed a way to do this with XmlDocument. Firstly, I had to convert the input string to a stream:
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
Once I had my stream, I was able to feed it into XmlDocument. Here's the full code:
string input = #"<?xml version="1.0" encoding="UTF-8"?>etc..";
byte[] byteArray = Encoding.UTF8.GetBytes(input);
var stream = new MemoryStream(byteArray);
var doc = new XmlDocument();
var nodes = doc.SelectNodes(xpath);
using (var tr = new XmlTextReader(stream))
{
tr.Namespaces = false;
doc.Load(tr);
}

C# Read web site xml file

I have one function which is
string fileToImport="C:\test.xml";
FileInfo fi = new FileInfo(fileToImport);
XmlDocument doc = new XmlDocument();
doc.Load(fileToImport);
This is point exact location of file.
But I want to use same function and import xml file from website.
For example I have below location.
http://testweb:1000/testdir/test.xml
Then I should open that location xml file and put in to the same way
FileInfo fi = new FileInfo(fileToImport);
XmlDocument doc = new XmlDocument();
doc.Load(fileToImport);
Anyone has best idea to get import this?
Thanks,
You should try
using (var client = new WebClient())
{
using (var reader = new StringReader(client.DownloadString("http://testweb:1000/testdir/test.xml")))
{
XmlDocument doc = new XmlDocument();
doc.Load(reader);
}
}
Also you can write this without WebClient&StringReader:
XmlDocument doc = new XmlDocument();
doc.Load("http://testweb:1000/testdir/test.xml");
More at https://msdn.microsoft.com/de-de/library/system.net.webclient(v=vs.110).aspx

convert json to xml and save result to a file

I'm converting a JSON string to an XML node like this:
public ActionResult Test(string json)
{
System.Xml.XmlNode myXmlNode = JsonConvert.DeserializeXmlNode("{\"root\":" + json + "}", "root");
How can I save myXmlNode to an external file, say test.xml?
Thanks
This should do it:
var xdoc = XDocument.Load(new StringReader(myXmlNode.ToString()), LoadOptions.None);
xdoc.Save(#"c:\temp\test.xml", SaveOptions.None);
UPDATE:
using (StreamWriter writer = new StreamWriter(Server.MapPath("~/test.xml")))
{
writer.WriteLine(myXmlNode.OuterXml);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXmlNode);
XmlTextWriter writer = new XmlTextWriter("yourfilename.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);

Add An XML Declaration To String Of XML

I have some xml data that looks like..
<Root>
<Data>Nack</Data>
<Data>Nelly</Data>
</Root>
I want to add "<?xml version=\"1.0\"?>" to this string. Then preserve the xml as a string.
I attempted a few things..
This breaks and loses the original xml string
myOriginalXml="<?xml version=\"1.0\"?>" + myOriginalXml;
This doesnt do anything, just keeps the original xml data with no declaration attached.
XmlDocument doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8","no");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string xmlString = sw.ToString();
This is also not seeming to have any effect..
XmlDocument doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
MemoryStream xmlStream = new MemoryStream();
doc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position = 0;
doc.Load(xmlStream);
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string xmlString = sw.ToString();
Use an xmlwritersettings to achieve greater control over saving. The XmlWriter.Create accepts that setting (instead of the default contructor)
var myOriginalXml = #"<Root>
<Data>Nack</Data>
<Data>Nelly</Data>
</Root>";
var doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
var ms = new MemoryStream();
var tx = XmlWriter.Create(ms,
new XmlWriterSettings {
OmitXmlDeclaration = false,
ConformanceLevel= ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8 });
doc.Save(tx);
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());

How can I remove the BOM from XmlTextWriter using C#?

How do remove the BOM from an XML file that is being created?
I have tried using the new UTF8Encoding(false) method, but it doesn't work. Here is the code I have:
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(filename, new UTF8Encoding(false));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("items");
xmlWriter.Close();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
XmlElement item = xmlDoc.CreateElement("item");
root.AppendChild(item);
XmlElement itemCategory = xmlDoc.CreateElement("category");
XmlText itemCategoryText = xmlDoc.CreateTextNode("test");
item.AppendChild(itemCategory);
itemCategory.AppendChild(itemCategoryText);
xmlDoc.Save(filename);
You're saving the file twice - once with XmlTextWriter and once with xmlDoc.Save. Saving from the XmlTextWriter isn't adding a BOM - saving with xmlDoc.Save is.
Just save to a TextWriter instead, so that you can specify the encoding again:
using (TextWriter writer = new StreamWriter(filename, false,
new UTF8Encoding(false))
{
xmlDoc.Save(writer);
}
I'd write the XML to a string(builder) instead and then write that string to file.

Categories