1

我在从 Linq 到 XML 查询返回数据时遇到问题。我有以下 XML

<sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/sdnList.xsd">
  <publshInformation>
    <Publish_Date>03/14/2013</Publish_Date>
    <Record_Count>5440</Record_Count>
  </publshInformation>
</sdnList>

我正在尝试使用以下方法获取 Publish Date 的值

XDocument xDoc = XDocument.Load(fileName);
XNamespace xNS = "http://tempuri.org/sdnList.xsd";
XNamespace xNS1 = "http://www.w3.org/2001/XMLSchema-instance";
string strCurrentDate = xDoc.Element(xNS1 + sdnList").Element("publshInformation").Element("Publish_Date").Value; 

这只是返回一个对象预期的错误。我知道我的问题在于命名空间(很可能是一个简单的解决方案)

谢谢

4

2 回答 2

2

该文档中的所有元素都在http://tempuri.org/sdnList.xsd名称空间中,因此您需要类似

xDoc.Element(xNS + "sdnList")
    .Element(xNS + "publshInformation")
    .Element(xNS + "Publish_Date").Value;
于 2013-03-18T15:13:49.490 回答
1

这将起作用:

XNamespace xNS = "http://tempuri.org/sdnList.xsd";
string strCurrentDate = xDoc.Element(xNS + "publshInformation").Element(xNS + "Publish_Date").Value;
于 2013-03-18T15:28:57.217 回答