[英]C# Load Datatable from LinQ XDocument using Using XPath where Xpath not known at compile time
我有一個LinQ XDocument(來自SOAP響應),我想將其轉換為數據表。 這是我要處理的XML。 它使用名稱空間使問題進一步復雜化。
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:getDetailsResponse xmlns:ns2="http://service.xyz.com/">
<return>
<meeting meetingCode="8">
<meetingDate>2013-07-08T00:00:00+10:00</meetingDate>
<actionList>
<actionCoOrdinator>The action man</actionCoOrdinator>
<action>
<actionType>Type1</actionType>
<actionBy>John</actionBy>
</action>
<action>
<actionType>Type2</actionType>
<actionBy>Mary</actionBy>
</action>
<action>
<actionType>Type3</actionType>
<actionBy>Phil</actionBy>
</action>
</actionList>
</meeting>
</return>
</ns2:getDetailsResponse>
</soap:Body>
</soap:Envelope>
這是想要在DataTable中的輸出
MeetingCode MeetingDate ActionCoOrdinator ActionType ActionBy ----------- ------------------------- ----------------- ---------- -------- 8 2013-07-08T00:00:00+10:00 The action man Type1 John 8 2013-07-08T00:00:00+10:00 The action man Type2 Mary 8 2013-07-08T00:00:00+10:00 The action man Type3 Phil
如您所見,我要為“ actionList”中的每個“ action”元素都需要一行,但是對於每一行,我還需要一些來自父/祖父母元素的信息。 在此階段,我所擁有的只是一個使用以下代碼的XDocument。
XDocument myXDoc = XDocument.Parse(soapStringResult);
我在該站點上看到過各種有關從XDocument提取數據的文章,但是我的問題是我所需的數據項事先是未知的。 我的起點是代表“行”的xPath。 Xpath是
ns2:getDetailsResponse/return/meeting/actionList/action
然后,我有一個數據庫表,其中包含我想要相對於此Xpath的所有數據項。 桌子看起來像這樣
XpathDataItem --------------------- ../../@meetingCode ../../meetingDate ../actionCoOrdinator actionType actionBy
當我知道要查找的數據項的Xpath時,就可以將數據加載到DataTable中,但是我不知道如何使用一組未知的XPath來進行處理。
預先感謝約翰
哪一部分未知? 要檢索的起點還是單個元素? 您的問題不清楚。 如果您根本不知道起點,那么Linq-to-xml將對此非常有用。
Linq-to-xml通常不會基於xpath檢索元素。 Elements()
和Descendants()
方法允許您在不知道特定路徑的情況下查詢xml數據。
要獲取meetingDate
而不管其路徑是什么,可以使用Descendants()
方法,如下所示:
var meetingDateElement = myXDoc.Descendants("meetingDate").SingleOrDefault;
if (meetingDateElement != null) {
var meetingDate = meetingDateElement.Value;
}
meetingCode
和actionCoOrdinator
可以類似的方式找到。
要獲得所有action
元素,您myXDoc.Descendants("action")
使用myXDoc.Descendants("action")
。 這樣的事情將為您提供每個操作的值:
var actions = from a in myXDoc.Descendants("action")
select new {
actionType = a.Element("actionType").Value,
actionBy = a.Element("actionBy").Value
};
如果您要解析的xml可能包含多個meeting
元素,那么您將使用`myXDoc.Descendants(“ meeting”)來獲取所有會議並在查詢或foreach語句中檢索子元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.