我的XML具有以下结构:
<?xml version="1.0"?>
<NidanArchiveDS>
<xs:schema id="NidanArchiveDS" targetNamespace="http://tempuri.org/NidanArchiveDS.xsd" xmlns:mstns="http://tempuri.org/NidanArchiveDS.xsd" xmlns="http://tempuri.org/NidanArchiveDS.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:element name="NidanArchiveDS" msdata:IsDataSet="true" msdata:Locale="ru-RU">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Settings">
<xs:complexType>
<xs:attribute name="ContentTypeName" form="unqualified" type="xs:string" use="required" />
<xs:attribute name="ListName" form="unqualified" type="xs:string" use="required" />
<xs:attribute name="DocTypeFieldName" form="unqualified" type="xs:string" />
<xs:attribute name="DocNumberFieldName" form="unqualified" type="xs:string" />
<xs:attribute name="DOcDateFieldName" form="unqualified" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:Settings" />
<xs:field xpath="@ContentTypeName" />
<xs:field xpath="@ListName" />
</xs:unique>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NidanArchiveDS xmlns="http://tempuri.org/NidanArchiveDS.xsd">
<Settings diffgr:id="Settings1" msdata:rowOrder="0" ContentTypeName="CONTENTTYPE 1" ListName="Заявки на оплату" DocTypeFieldName="Имя11" DocNumberFieldName="Имя22" DOcDateFieldName="Имя33" />
<Settings diffgr:id="Settings2" msdata:rowOrder="1" ContentTypeName="CONTENTTYPE 2" ListName="LST" DocTypeFieldName="Имя44" DocNumberFieldName="Имя" DOcDateFieldName="Имя5555" />
</NidanArchiveDS>
下面是我使用ContentTypeName =“CONTENTTYPE 2”获取设置的查询
docNameFieldName = (from xn in nidanarchiveSettings.Descendants(System.Xml.Linq.XName.Get("Settings"))
where xn.Attribute(System.Xml.Linq.XName.Get("ContentTypeName")).Value == "CONTENTTYPE 2"
&& xn.Attribute(System.Xml.Linq.XName.Get("ListName")).Value == "LST"
select xn.Attribute(System.Xml.Linq.XName.Get("DocTypeFieldName")).Value).SingleOrDefault();
但它给了我一个空字符串。我想知道如何以正确的方式编写查询以获得此属性。
答案 0 :(得分:1)
你忘记了命名空间:
XDocument xdoc = XDocument.Load(path_to_xml);
XNamespace ns = "http://tempuri.org/NidanArchiveDS.xsd";
var docNameFieldName =
(from s in xdoc.Descendants(ns + "Settings")
where (string)s.Attribute("ContentTypeName") == "CONTENTTYPE 2" &&
(string)s.Attribute("ListName") == "LST"
select (string)s.Attribute("DocTypeFieldName")).SingleOrDefault();
也不要使用节点的Value
属性。简单地将它转换为字符串(或其他类型) - 如果某个节点丢失,它不会引发异常。
答案 1 :(得分:0)
你可以用lambda路线:
var docNameFieldName = xdoc.Descendants("Settings")
.First(sett => sett.Attribute("ContentTypeName") == "CONTENTTYPE 2")
.Attribute("DocTypeFieldName").Value;
此外,您可能刚刚发布了部分XML片段,但您的<diffgr:diffgram>
代码未关闭...