如何使用.Net将字符串转换为XML [英] how to convert string to XML using .Net

查看:176
本文介绍了如何使用.Net将字符串转换为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的开发人员,我将XML输出存储为String,然后再次将该字符串转换为XML.我成功将XML输出转换为String,但是再次将字符串转换为XML时出现问题.
我分享我的代码

Dear Developer I store the XML output to String and Again convert this string to XML .I successfully convert XML output to String, but i got problem again converting string to XML.
I share my code

webservice.Service1 objService1 = new webservice.Service1();
       String s = objService1.HelloWorld();   //Convert XML output into String
       XmlDocument xd = new XmlDocument();
       xd.LoadXML(s);



我使用LoadXML()方法,但出现错误根级别的数据无效.第1行位置1". .如果有任何机构给出正确的代码将c#中的String转换为XML,那么这非常有用.

在此先谢谢
问候,
Ravi



I use LoadXML() method, but i got error "Data at the root level is invalid. Line 1 position 1." .Its greatful, if any body give right code to convert String To XML in c#.

Thanks In advance
Regards,
Ravi

推荐答案

这段代码对我来说没问题.我认为问题出在您的xml数据上.
一些建议:

1.)您可以确认XML格式正确吗?您是否尝试过使用IE打开XML文件并确保没有错误?
2.)确保根元素前没有空格.
The piece of code looks ok to me. I think the problem is with your xml data.
A few suggestions:

1.) Can you confirm that the XML is well formed? Have you tried to open the XML file using IE and ensuring that there are no errors?
2.) Make sure there is no blank space before the root element.


我认为我注意到的是变量不匹配.将"s1"传递给LoadXML()方法时,您可以将XML字符串化为"s"变量.

您只需将"s"的输出保存在XML文件中,就可以确保从字符串(即本例中的变量"s")生成XML.

希望对您有所帮助.
One think I have noticed is the variable mismatch. You have XML to string in "s" variable while you are passing "s1" to the LoadXML() method.

You can ensure the XML generation from string (i.e. from variable "s" in this case), by simply saving the output of "s" in a XML file.

Hope it helps.


考虑到Manav的观点,您一定错过了XML声明.

试试这个:
字符串s =<?xml版本= \" 1.0 \?>" + objServicel.HelloWorld();

现在加载:xd.LoadXml(s);

现在工作了吗?
Considering Manav''s points, you must have missed the XML Declaration.

try this:
string s = "<?xml version = \"1.0\"?>" + objServicel.HelloWorld();

Now load : xd.LoadXml(s);

Did it work now?


这篇关于如何使用.Net将字符串转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆