下面的这段 XML 是一个更大的 XML 的一部分。我一遍又一遍地尝试获取地址行 1、2、3 以及城市和州、邮政编码和国家/地区。我想把它功能化,这样我就可以挑选出来 那些基于 InvoiceHeader id="XXXX"的地址但是我一直碰壁。 我尝试了下面的查询或类似的查询,但我一直收到错误对象引用未设置为对象的实例。
这是我的查询,有人可以指出我明显的错误吗。
IEnumerable<string> partNos =
from item in PurchaseOrderXml.Descendants("RemitTo").Descendants("Address")
where (string)item.Attribute("id").Value == "23951768"
select (string)item;
<Invoice>
<InvoiceHeader id="23951768" status="InProcess">
<InvoiceName />
<InvoiceNumber>23951768</InvoiceNumber>
<InvoiceDate>2014-09-26 00:00:00.0</InvoiceDate>
<DueDate>2014-10-26 00:00:00.0</DueDate>
<SupplierInvoiceNo>534254504</SupplierInvoiceNo>
<InvoiceType>Invoice</InvoiceType>
<Supplier id="3825405">
<ContactInfo type="main">
<Address>
<AddressLine lineNumber="1">Post </AddressLine>
<AddressLine lineNumber="2">30 Street</AddressLine>
<AddressLine lineNumber="3">30 Street</AddressLine>
<City>Saint Louis</City>
<State>MO</State>
<PostalCode>63103-2530</PostalCode>
<Country isoCountryCode="US">United States</Country>
</Address>
</ContactInfo>
</Supplier>
<BillTo>
<Address>
<AddressLine lineNumber="1">vvvv</AddressLine>
<AddressLine lineNumber="2">vvvv</AddressLine>
<City>Philadelphia</City>
<State>PA</State>
<PostalCode>19222</PostalCode>
<Country isoCountryCode="US">United States</Country>
</Address>
</BillTo>
<RemitTo>
<Address>
<AddressLine lineNumber="1">P O BOX 535182</AddressLine>
<AddressLine lineNumber="2" />
<AddressLine lineNumber="3" />
<City>ATLANTA</City>
<State>GA</State>
<PostalCode>303535182</PostalCode>
<Country isoCountryCode="US">United States</Country>
</Address>
</RemitTo>
</InvoiceHeader>
</Invoice>
最佳答案
您的项目范围变量对应于一个没有 id 属性的 Address 元素。相反,您需要一个查询,它首先查找(或过滤)适当的 InvoiceHeader,然后查找匹配的 InvoiceHeader 的 Address 元素后代。
这是一个查找 InvoiceHeader 的示例:
var Header = PurchaseOrderXml.Descendants("InvoiceHeader")
.FirstOrDefault(header => (string)header.Attribute("id").Value == headerId);
您可以检查是否找到 header (Header != null
)。一旦你有了标题,就可以在给定元素的范围内做任何你需要做的事情。示例:
var RemitToAddress = Header.Descendants("RemitTo").Descendants("Address").FirstOrDefault();
您可能想要检查 header 中的其他元素,因此将查询拆分成这样的部分可以使您的意图清晰。
另请注意,我使用了 Descendants
,但如果它更符合您的架构,您也可以使用 Elements
。
另一个例子,要获取 AddressLine
元素并连接它们,您可以尝试以下方式:
IEnumerable<string> AddressLines = RemitToAddress.Elements("AddressLine")
.OrderBy(line => (int)line.Attribute("lineNumber"))
.Select(line => line.Value);
var AddressText = string.Join("\n", AddressLines);
关于c# - 使用 Linq to XML 检索 xml 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581131/