0

当我如下调用我的服务时,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();

    }
4

1 回答 1

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;
}
于 2012-05-17T18:17:13.633 回答