简体   繁体   English

使用多个NameSpaces C#从XML文件返回数据

[英]Returning Data from XML file with Multiple NameSpaces C#

I am having trouble returning data from a Linq to XML query. 我无法将数据从Linq返回到XML查询。 I have the following 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>

I am trying to get the value of Publish Date using the following 我试图使用以下内容获取发布日期的值

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; 

This just returns an object expected error. 这只是返回一个对象预期错误。 I know my problem is around the namespaces (and most likely is will be a simple solutions) 我知道我的问题在于名称空间(并且很可能是一个简单的解决方案)

Thanks 谢谢

All the elements in that document are in the http://tempuri.org/sdnList.xsd namespace, so you need something like 该文档中的所有元素都在http://tempuri.org/sdnList.xsd命名空间中,因此您需要类似的东西

xDoc.Element(xNS + "sdnList")
    .Element(xNS + "publshInformation")
    .Element(xNS + "Publish_Date").Value;

This will work: 这将有效:

XNamespace xNS = "http://tempuri.org/sdnList.xsd";
string strCurrentDate = xDoc.Element(xNS + "publshInformation").Element(xNS + "Publish_Date").Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM