如何用Linq to XML查询这个属性值

本文关键字:属性 查询 XML 何用 Linq to | 更新日期: 2023-09-27 18:12:27

我有一个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;

我做错了什么?

如何用Linq to XML查询这个属性值

您需要包含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;