如何使用Linq to XML查询此属性值

时间:2015-09-11 18:16:35

标签: c# xml linq-to-xml

我有一个XML文档,格式如下:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:blah:-myXSD-2007-03-14T00-26-45" solutionVersion="1.0" productVersion="15.0.0.0" PIVersion="1.0.0.0" href="http://blah/FormServerTemplates/blah.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-03-14T00:26:45" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
    <my:workDay>MON-FRI</my:workDay>
</my:myFields>

我尝试使用以下代码查询workday,但获得了null

var xdoc = XDocument.Load(file);

var workDay = from x in xdoc.Descendants("workDay")
              select x.Value;

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您需要包含my:的命名空间:

 var xdoc = XDocument.Load(file);
 XNamespace myNamespace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-03-14T00:26:45";

 var workDay = from x in xdoc.Descendants(myNamespace + "workDay")
               select x.Value;