C#使用XPath从LinQ XDocument加载数据表,其中XPath在编译时未知
我有一个LinQ XDocument(来自SOAP响应),我想将其转换为数据表。下面是我正在处理的XML。它使用名称空间使问题进一步复杂化C#使用XPath从LinQ XDocument加载数据表,其中XPath在编译时未知,c#,xpath,datatable,namespaces,linq-to-xml,C#,Xpath,Datatable,Namespaces,Linq To Xml,我有一个LinQ XDocument(来自SOAP响应),我想将其转换为数据表。下面是我正在处理的XML。它使用名称空间使问题进一步复杂化 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <ns2:getDetailsResponse xmlns:ns2="http://service.xyz.com/">
<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>
我在这个网站上看到过关于从XDocument中提取数据的各种帖子,但我的问题是我想要的数据项事先不知道。我的出发点是表示“行”的xPath。Xpath是
ns2:getDetailsResponse/return/meeting/actionList/action
然后我有一个DB表,其中包含我想要的与这个Xpath相关的所有数据项。这张桌子看起来像这样
XpathDataItem
---------------------
../../@meetingCode
../../meetingDate
../actionCoOrdinator
actionType
actionBy
XpathDataItem
---------------------
..//@meetingCode
../../会议日期
../actionCoOrdinator
动作类型
诉讼人
当我知道要查找的数据项的XPath时,我可以将数据加载到DataTable中,但我不知道如何使用未知的XPath集
提前谢谢
约翰哪个部分是未知的?要检索的起点或单个元素?你的问题不清楚。如果您只是不知道起点,那么LINQtoXML将非常适合这一点 LINQtoXML通常不会基于xpath检索元素。
Elements()
和subjects()
方法允许您在不知道具体路径的情况下查询xml数据
要检索meetingDate
,无论其路径是什么,您可以使用如下subjections()
方法:
var meetingDateElement = myXDoc.Descendants("meetingDate").SingleOrDefault;
if (meetingDateElement != null) {
var meetingDate = meetingDateElement.Value;
}
meetingCode
和actionCoOrdinator
可以以类似的方式找到
要获得所有的动作
元素,只需使用myXDoc.substands(“动作”)
。类似这样的操作将获得每个操作的值:
var actions = from a in myXDoc.Descendants("action")
select new {
actionType = a.Element("actionType").Value,
actionBy = a.Element("actionBy").Value
};
如果您正在解析的xml可能包含多个meeting
元素,那么您将使用`myXDoc.subjects(“meeting”)获取所有会议并检索查询或foreach语句中的子元素
var meetingDateElement = myXDoc.Descendants("meetingDate").SingleOrDefault;
if (meetingDateElement != null) {
var meetingDate = meetingDateElement.Value;
}
var actions = from a in myXDoc.Descendants("action")
select new {
actionType = a.Element("actionType").Value,
actionBy = a.Element("actionBy").Value
};