[英]Retrieving XML from a C# function on WCF
我有一个WCF服务,用于通过URL调用C#函数,这是我用于url的代码:
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml, UriTemplate = "?GetValuesVar={Var}")]
string getHisUmsTimeRedVar(string Var);
一旦知道我正在使用URL的参数来调用函数并检索值。 我的问题是所有XML代码都在<string></string>
标记之间。
<string>
<?xml version="1.0"?><ArrayOfHistoricVal
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<HistoricVal>
<Date>2016-05-31T22:00:00</Date><Value>2060</Value>
</HistoricVal>
</ArrayOfHistoricVal>
</string>
有没有办法以普通XML而不是在这两个<string></string>
标记之间检索此值?
编辑:要获取的值在这样的函数中:
public string getHisUmsTimeRedVar(string idVar)
{
try
{
ADAMUtil.Log.info("getHisUmsTimeRed. Empieza = ");
DateTime FechaIni = new DateTime(2015, 05, 05, 0, 0, 0);
DateTime FechaFin = new DateTime(2018, 05, 05, 0, 0, 0);
List<HistoricVal> list = new List<HistoricVal>();
List<His> Historicos = null;
ADAMUtil.Log.info("getHisUmsTimeRed. Empieza1 = ");
Historicos = getHisUmsTimeRed("admin", "admin", Convert.ToInt64(idVar), 14, null, 0, 0, FechaIni, FechaFin, 0, "Romance Standard Time");
ADAMUtil.Log.info("getHisUmsTimeRed. Historicos = " + Historicos.Count);
for (int i = 0; i < Historicos.Count; i++)
{
HistoricVal item = new HistoricVal();
item.Date = Historicos[i].IniDat;
item.Value = Historicos[i].Val;
list.Add(item);
}
String xmlDoc;
xmlDoc = toXML.VartoXML(list);
//Browser.BrowserOpen();
return xmlDoc;
}
catch (Exception ex)
{
ADAMUtil.Log.info("getHisUmsTimeRed. ex = " + ex.ToString() + ex.StackTrace.ToString());
return null;
}
}
并且webinvoke必须是Stream,而不是字符串。
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml, UriTemplate = "?GetValuesVar={Var}")]
stream getHisUmsTimeRedVar(string Var);
XML字符串的问题在于它是错误的XML:XML声明应该从头开始。 您不能像这样轻易地将其转换为XElement或XDocument。
因此,有两种解决方案:
自己使用字符串来删除其他标签。 该解决方案对于更改或边缘情况而言并不可靠,建议您使用第一个解决方案。 但是,如果您无法更改调用的方法,则至少可以帮助您:
//Trims 8 characters (<string>) at the beginning and 9 at the end. String correctString = yourString.Substring(8, yourString.Length - 17);
编辑:在评论中讨论了这个问题之后,似乎只有浏览器显示了<string>
标记,并且它们不在XML文件中。 这是由于它很有可能将您的字符串对象序列化。 通过自己对其进行序列化并将其通过XElement.Parse()
传递给浏览器,或者直接更改对象的类型,浏览器便能够理解其应显示的内容。
更改
public string getHisUmsTimeRedVar
至
public XDocument getHisUmsTimeRedVar
返回不包含在字符串标记中的正确xml。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.