如何在 C# 中读取 XML 文档并将输出显示为字符串

Pat*_*tan -1 c# asp.net xmldocument xmlreader

考虑我的源文件看起来像这样。

        <Content xmlns="uuid:4522eb85-0a47-45f9-8e2b-1x82c78xx920">
            <first>Hello World.This is Fisrt field</first>
            <second>Hello World.This is second field</second>
   </Content>
Run Code Online (Sandbox Code Playgroud)

我想编写一段代码,从某个位置读取此 xml 文档并将其显示为字符串。

  say name of the xml file is helloworld.xml.
  Location: D:\abcd\cdef\all\helloworld.xml.
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下操作,但我无法做到。

            XmlDocument contentxml = new XmlDocument();
            contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml");
            Response.Write("<BR>" + contentxml.ToString());
Run Code Online (Sandbox Code Playgroud)

Response.write 不显示任何内容。如果我错过了什么,请纠正我。它没有创建任何组件并且错误即将到来。

我也尝试过这个,

            XmlDocument contentxml = new XmlDocument();
            try
            {
                 contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml");
             }
            catch (XmlException exp)
            {
                Console.WriteLine(exp.Message);
            }
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            contentxml.WriteTo(xw);
            Response.Write("<BR>" + sw.ToString());
Run Code Online (Sandbox Code Playgroud)

但我没有找到任何输出。

我想从某个位置读取 XML 文件并将其显示为字符串。

任何人都可以帮忙解决这个问题吗?

谢谢你,穆齐米尔。

Bro*_*ass 5

您需要以下OuterXml财产:

Response.Write("<BR>" + contentxml.OuterXml);
Run Code Online (Sandbox Code Playgroud)

另外,您正在加载一个文件而不是 xml,所以使用

  contentxml.Load(@"D:\abcd\cdef\all\helloworld.xml");
Run Code Online (Sandbox Code Playgroud)

代替

  contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml");
Run Code Online (Sandbox Code Playgroud)