我收到以下错误:
"Data at the root level is invalid. Line 1, position 1."
以下是WEB APIpartial代码:
//POST api/RunningValue_Import
public object PostRunningValue(HttpRequestMessage xml)
{
try
{
#region Retrieve XML string and Create XDocument
//the method below generates the same error:
//string tempXmlString = xml.Content.ReadAsStringAsync().Result;
//TextReader tr = new StringReader(tempXmlString);
//XDocument doc = XDocument.Load(tr);
XDocument doc = XDocument.Load(xml.Content.ReadAsStreamAsync().Result); //<=== ERROR!
#endregion
jQuery的:
var inputText = inputText.replace(/ /g, ''); //eliminate spaces
inputText = inputText.replace(/\"/g, '\\"'); //escape double quotes
$.ajax({
type: "POST",
url: reqUrl,
data: inputText,
datatype: "text",
contentType: "text/xml"
});
inputText变量内容:
inputText = "\\\"<?xmlversion=\\\"1.0\\\"encoding=\\\"utf-8\\\"standalone=\\\"yes\\\"?>\n<server>\n<networkAdapters>\n<networkAdapterid=\\\"3d9c0d9d-d353-4d78-b034-b29f2dd824a0\\\">\n</networkAdapter>\n</networkAdapter>\n</server>\\\""
传递原始XMl字符串:
"<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<server>
<networkAdapters>
<networkAdapter id="3d9c0d9d-d353-4d78-b034-b29f2dd824a0">
</networkAdapter>
</networkAdapter>
</server>"
答案 0 :(得分:0)
删除所有空格会导致问题。如果我取消引号和斜杠,你会发现它不是有效的XML:
<?xmlversion="1.0"encoding="utf-8"standalone="yes"?><server><networkAdapters><networkAdapterid="3d9c0d9d-d353-4d78-b034-b29f2dd824a0"></networkAdapter></networkAdapter></server>
如果您尝试将其格式化以便于阅读,它看起来像这样:
<!-- This declaration is invalid without spacing -->
<?xmlversion="1.0"encoding="utf-8"standalone="yes"?>
<server>
<networkAdapters>
<!-- This should read "networkAdapter id" not "networkAdapterid" -->
<networkAdapterid="3d9c0d9d-d353-4d78-b034-b29f2dd824a0"></networkAdapter>
<!-- This should be a closing bracket for networkAdapters, not networkAdapter -->
</networkAdapter>
</server>