C# 使用 .Net 将字符串转换为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16640962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to XML using .Net
提问by james raygan
I store the XMLoutput to Stringand Again convert this string to XML .I successfully convert XMLoutput to String, but i got problem again converting string to XML.
我将XML输出存储到String并再次将此字符串转换为 XML。我成功地将XML输出转换为字符串,但我再次将字符串转换为 XML 时遇到问题。
sample code:
示例代码:
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXML(s);
I use LoadXML()method, but i got error
我使用LoadXML()方法,但出现错误
Data at the root level is invalid. Line 1 position 1.
Its grateful, if any body give right code to convert String To XML in c#. Thank you,
如果有人提供正确的代码将字符串转换为 C# 中的 XML,它会很感激。谢谢,
采纳答案by SyntaxError
You should use XDocument. XDocumentis better than XMLDocument. It is very efficient, simple and easy to use.
您应该使用XDocument。XDocument比XMLDocument 好。它非常高效、简单且易于使用。
Your code :
你的代码:
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXml(s);
Solution:
解决方案:
XDocument xd = XDocument.Parse(s);
回答by Chachi
XmlDocument xd = new XmlDocument();
xd.LoadXml("<root>123</root>");
It works.
You should print the svalue and check it is a valid xml string.
有用。您应该打印该s值并检查它是否是有效的 xml 字符串。

