路径中的XML非法字符

Kev*_*vin 68 c# xml

我正在查询基于soap的服务,并希望分析返回的XML,但是当我尝试将XML加载到XDoc中以查询数据时.我收到'路径中的非法字符'错误消息?这(下面)是从服务返回的XML.我只是想获得比赛列表并将它们放入我已设置的列表中.XML确实加载到XML文档中,但必须正确格式化?

任何有关如何做到这一点并绕过错误的最佳方法的建议将不胜感激.

<?xml version="1.0" ?> 
- <gsmrs version="2.0" sport="soccer" lang="en" last_generated="2010-08-27 20:40:05">
- <method method_id="3" name="get_competitions">
  <parameter name="area_id" value="1" /> 
  <parameter name="authorized" value="yes" /> 
  <parameter name="lang" value="en" /> 
  </method>
  <competition competition_id="11" name="2. Bundesliga" soccertype="default" teamtype="default" display_order="20" type="club" area_id="80" last_updated="2010-08-27 19:53:14" area_name="Germany" countrycode="DEU" /> 
  </gsmrs>
Run Code Online (Sandbox Code Playgroud)

这是我的代码,我需要能够在XDoc中查询数据:

string theXml = myGSM.get_competitions("", "", 1, "en", "yes");
XmlDocument myDoc = new XmlDocument();
MyDoc.LoadXml(theXml);
XDocument xDoc = XDocument.Load(myDoc.InnerXml);
Run Code Online (Sandbox Code Playgroud)

Ond*_*cny 220

你没有显示你的源代码,但我猜你在做什么是这样的:

string xml = ... retrieve ...;
XmlDocument doc = new XmlDocument();
doc.Load(xml); // error thrown here
Run Code Online (Sandbox Code Playgroud)

Load方法需要文件名而不是XML本身.要加载实际的XML,只需使用以下LoadXml方法:

... same code ...
doc.LoadXml(xml);
Run Code Online (Sandbox Code Playgroud)

同样,使用XDocumentLoad(string)方法需要文件名,而不是实际的XML.但是,没有LoadXml方法,所以从字符串加载XML的正确方法是这样的:

string xml = ... retrieve ...;
XDocument doc;
using (StringReader s = new StringReader(xml))
{
    doc = XDocument.Load(s);
}
Run Code Online (Sandbox Code Playgroud)

事实上,在开发任何东西时,注意参数的语义(含义)而不仅仅是它们的类型是一个非常好的主意.当参数的类型是a时,string它并不意味着只能输入任何字符串.

另外,在关于更新的问题,这是没有意义的使用XmlDocument,并XDocument在同一时间.选择一个或另一个.

  • 谢谢回复.这可以将它加载到XMLDocument中,但是如果我尝试将此XML加载到XDoc中以查询数据,我仍然会在路径中获取非法字符.有任何想法吗?string theXml = myGSM.get_competitions("","",1,"en","yes"); XmlDocument myDoc = new XmlDocument(); myDoc.LoadXml(theXml); XDocument xDoc = XDocument.Load(myDoc.InnerXml); (2认同)

Har*_*vey 9

跟进Ondrej Tucny的回答:

如果您想使用xml字符串,可以使用XElement,并调用"parse"方法.(因为您的需求,XElement和XDocument将满足您的需求)

例如 ;

string theXML = '... get something xml-ish...';
XElement xEle = XElement.Parse(theXML);

// do something with your XElement
Run Code Online (Sandbox Code Playgroud)

XElement的Parse方法允许您传入XML字符串,而Load方法需要文件名.