[英]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.