简体   繁体   中英

How to show parsed xml in TextBlock in WPF?

I have TextBlock with name XML_View , also I know .xml file location string filename = dlg.FileName;

So I want to show xml n that TextBlock , I found a possible solution here ( Display XML in a WPF textbox ), it gives as a function, like this:

protected string FormatXml(string xmlString)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlString);
    StringBuilder sb = new StringBuilder();
    System.IO.TextWriter tr = new System.IO.StringWriter(sb);
    XmlTextWriter wr = new XmlTextWriter(tr);
    wr.Formatting = Formatting.Indented;
    doc.Save(wr);
    wr.Close();
    return sb.ToString();
}

If I get required string, I might just simply write XML_View.Text = String_xml; or something like this. But I don't know how to get string if I have .xml file and I don't know how to use such a function.

I've modified your function to take as parameter the filename to read your xml from. Make sure the file exists in your bin directory (or you use an absolute path like @"C:\\temp\\myfile.xml" to resolve).

protected string FormatXml(string xmlFile)
{
    XmlDocument doc = new XmlDocument();
    FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
    doc.Load(fs);
    StringBuilder sb = new StringBuilder();
    System.IO.TextWriter tr = new System.IO.StringWriter(sb);
    XmlTextWriter wr = new XmlTextWriter(tr);
    wr.Formatting = Formatting.Indented;
    doc.Save(wr);
    wr.Close();
    return sb.ToString();
}

You can replace

doc.LoadXml(xmlString);

with

doc.Load(xmlFilePath);

I used this as reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM