当我在下面调用我的服务时,XML元素TruckName和Website为空?显然,元素在网页上的XML中是分开的(参见下面的xml)。我相信它与ArrayOf元素的关系是第一个?下面是我的控制台应用程序调用方法GetInfo()的代码。我是否需要摆脱ArrayOfFoodTruck元素?如果是这样,最简单的方法。感谢所有提前..
- <ArrayOfFoodTruck xmlns="http://schemas.datacontract.org/2004/07/WCFServiceLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
- <FoodTruck>
<Company i:nil="true" />
<DayOfWeek i:nil="true" />
<Location i:nil="true" />
<TimeOfDay i:nil="true" />
<TruckID>0</TruckID>
<TruckName>Truck 87</TruckName>
<Website>http://www.test.com</Website>
</FoodTruck>
- <FoodTruck>
<Company i:nil="true" />
<DayOfWeek i:nil="true" />
<Location i:nil="true" />
<TimeOfDay i:nil="true" />
<TruckID>0</TruckID>
<TruckName>Bon Me</TruckName>
<Website>http://www.test.com</Website>
</FoodTruck>
</ArrayOfFoodTruck>
这是我的控制台应用程序的调用..
static void GetInfo()
{
XElement rootXml = XElement.Load("http://localhost:5150/getnames");
var FoodTruck = from C in rootXml.Elements()
select new { TruckName = (string)C.Element("TruckName"), WebSite = (string)C.Element("Website") };
foreach (var x in FoodTruck)
Console.WriteLine("{0}\r\n{1}", x.TruckName, x.WebSite);
Console.ReadKey();
}
答案 0 :(得分:1)
我猜你的命名空间有问题
XDocument xDoc = XDocument.Load(.....);
XNamespace ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/WCFServiceLibrary");
var result = xDoc.Descendants(ns+"FoodTruck")
.Select(n => new
{
TruckName=n.Element(ns+"TruckName").Value,
WebSite = n.Element(ns+"Website").Value
})
.ToArray();
- 编辑 - 或
XmlSerializer ser = new XmlSerializer(typeof(FoodTruck[]), "http://schemas.datacontract.org/2004/07/WCFServiceLibrary");
var foodTrucks = (FoodTruck[])ser.Deserialize(new StringReader(xml));
public class FoodTruck
{
public string Website;
public string TruckName;
}