我从Web API的控制器收到了一个XML字符串,构造方式如下:
private string CreateXDoc(IEnumerable<PassedJSONConverted> passed)
{
XNamespace xmlns = "http://host.adp.com";
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
var jobListElement = new XElement(xmlns + "JobXML");
foreach (var objectItem in passed)
{
var loopElement = new XElement(xmlns + "JobsXML", new XElement(xmlns + "ID", objectItem.ID.ToString()), new XElement(xmlns + "Name", objectItem.Name), new XElement(xmlns + "Age", objectItem.Age.ToString()), new XElement(xmlns + "JobTitle", objectItem.JobTitle), new XElement(xmlns + "StartDate", objectItem.StartDate));
jobListElement.Add(loopElement);
}
doc.Add(jobListElement);
//Format without \n's
return doc.ToString(SaveOptions.DisableFormatting);
}
这很好,XML设置如下:
- <JobXML xmlns="http://host.xxx.com">
- <JobsXML>
<ID>1</ID>
<Name>Dave</Name>
<Age>23</Age>
<JobTitle>Developer</JobTitle>
<StartDate>10/24/2013 6:40:28 AM</StartDate>
</JobsXML>
- <JobsXML>
<ID>2</ID>
<Name>John</Name>
<Age>44</Age>
<JobTitle>QA</JobTitle>
<StartDate>10/24/2013 6:40:28 AM</StartDate>
</JobsXML>
- <JobsXML>
<ID>3</ID>
<Name>Dave</Name>
<Age>23</Age>
<JobTitle>Senior Developer</JobTitle>
<StartDate>10/24/2013 6:40:28 AM</StartDate>
</JobsXML>
</JobXML>
当我将其作为字符串返回并尝试像下面展示的那样解析回xDoc时:
private static string HandleResponse(HttpWebResponse httpResponse)
{
using (var responseReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
string responsePayload = responseReader.ReadToEnd();
var newxDoc = XDocument.Parse(responsePayload);
return responsePayload;
}
}
在运行时,字符串'responsePayLoad'的设置如下:
"<JobXML xmlns=\"http://host.adp.com\"><JobsXML><ID>1</ID><Name>Dave</Name><Age>23</Age><JobTitle>Developer</JobTitle><StartDate>10/24/2013 6:45:22 AM</StartDate></JobsXML><JobsXML><ID>2</ID><Name>John</Name><Age>44</Age><JobTitle>QA</JobTitle><StartDate>10/24/2013 6:45:22 AM</StartDate></JobsXML><JobsXML><ID>3</ID><Name>Dave</Name><Age>23</Age><JobTitle>Senior Developer</JobTitle><StartDate>10/24/2013 6:45:22 AM</StartDate></JobsXML></JobXML>"
这段文本在'newxDoc'对象处抛出XmlException异常:
未处理的XmlException。根级别上的数据无效。第一行,第一位置。
有人能告诉我哪里出错了吗?
XDocument.Parse()
,并且没有出现错误。 - Chuck SavageStreamReader
中将Encoding
设置为Default
对我有用。 - Andrei V