C# Read web site xml file - c#

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

Related

Xml File should create new line and leave the previous data

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

Read xml data file into Windows.Data.Xml.Dom.XMLDocument

How can we read a xml data file into Windows.Data.Xml.Dom.XMlDocument?
The following code is possible only for System.Xml.XmlDocument.
XmlDocument myxml = XmlDocument.Load("abc.xml");
I read the xml file content to a string, and then use LoadXml():
string fileContent;
StorageFile tileTemplateFile =
await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"<path to file>"));
using (StreamReader reader =
new StreamReader(await tileTemplateFile.OpenStreamForReadAsync()))
{
fileContent = await reader.ReadToEndAsync();
}
XmlDocument tileXml = new XmlDocument();
tileXml.LoadXml(fileContent);
I got most of the code from this answer.
You need to do the following.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(<string representation of your xml>);

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

how to save xmldocument to a stream

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

How to create rtf using xml xslt and c#

I have created an xml document and an xslt document and now i want to create a word doc/rtf using these through using c#.
I have found the following code on the internet however I can't find a way to use it because I'm not using datasets. I just want the program to read the xml and the xslt combine the two and create a word document
Any help would be really appreciated
DataSet ds;
XmlDataDocument xmlDoc;
XslCompiledTransform xslTran;
XmlElement root;
XPathNavigator nav;
XmlTextWriter writer;
try
{
//Create the DataSet from the XML file
ds = new DataSet();
ds.ReadXml("Employee.xml");
//Create the XML from the DataSet
xmlDoc = new XmlDataDocument(ds);
//Load the XSLT for Transformation
xslTran = new XslCompiledTransform();
xslTran.Load("Employee.xslt");
//Determine the Root object in the XML
root = xmlDoc.DocumentElement;
//Create the XPath Navigator to navigate throuth the XML
nav = root.CreateNavigator();
//First delete the RTF, if already exist
if (File.Exists("Employee.rtf"))
{
File.Delete("Employee.rtf");
}
//Create the RTF by Transforming the XML and XSLT
writer = new XmlTextWriter("Employee.rtf", System.Text.Encoding.Default);
xslTran.Transform(nav, writer);
//Close the Writer after Transformation
writer.Close();
//Release all objects
writer = null;
nav = null;
root = null;
xmlDoc = null;
ds = null;
MessageBox.Show("Document created successfully.....");
}
catch (Exception ex)
{
writer = null;
nav = null;
root = null;
xmlDoc = null;
ds = null;
MessageBox.Show(ex.StackTrace);
}
}
Read http://msdn.microsoft.com/en-us/library/0610k0w4.aspx, it tells you how to use XslCompiledTransform. If you want to transform from a file and output a file then all you need is
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("stylesheet.xslt");
proc.Transform("input.xml", "output.rtf");

Categories