2017-10-11 100 views
0

我一直在從Scott Allen的Puralsight course on Linq Fundamentals開始工作,此鏈接部分描述了使用命名空間前綴讀取xml,但我無法完成此工作。Linq到名稱空間前綴不起作用的XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<OutboundEvent 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="urn:abb.com:assetsuite:IF:Event http://apifw/devifa/xml/GeneralLedger/GeneralLedger.Publish.Event.V940.xsd" 
    xmlns="urn:abb.com:assetsuite:IF:Event" 
    xmlns:hdr="urn:abb.com:assetsuite:IF:Header" 
    xmlns:bo="urn:abb.com:assetsuite:IF:BO" 
    xmlns:boe="urn:abb.com:assetsuite:IF:IFExtension" 
> 
... 
    <bo:BusinessObject> 
    ... 
    </bo:BusinessObject> 
</OutboundEvent> 

我應該得到一個單一的XElement從下面的代碼返回,但我並不:

var document = XDocument.Load(path); 
var bo = (XNamespace)"urn:abb.com:assetsuite:IF:BO"; 

var businessobjects = 
    from elements in document.Element("OutboundEvent")?.Elements(bo + "BusinessObject") 
     ?? Enumerable.Empty<XElement>() 
    select elements; 
+0

請勿截取_text _...後的實際文字。 –

+0

粘貼跨越多頁的XML的最佳方式是什麼? – CodenameCain

+0

粘貼XML的相關部分,它不需要是全文。足以說明問題。 –

回答

2

OutboundEvent節點是命名空間,但你的代碼引用它,就好像它是不是。它位於urn:abb.com:assetsuite:IF:Event命名空間中。

XNamespace ns = "urn:abb.com:assetsuite:IF:Event"; 
XNamespace bo = "urn:abb.com:assetsuite:IF:BO"; 
var businessObjects = 
    document.Elements(ns + "OutboundEvent").Elements(bo + "BusinessObject"); 
+0

它實際上在默認名稱空間中。但是,是的,應該定義和使用默認的命名空間。 –

+1

對不起,默認命名空間不適合它。我忘記了它叫什麼。根?空? –

1

不應該爲OutboundEvent元素定義和使用默認命名空間嗎?

var document = XDocument.Load(path); 
var ns = (XNamespace)"urn:abb.com:assetsuite:IF:Event"; 
var bo = (XNamespace)"urn:abb.com:assetsuite:IF:BO"; 

var businessobjects = 
    from elements in document.Element(ns + "OutboundEvent")?.Elements(bo + "BusinessObject") 
     ?? Enumerable.Empty<XElement>() 
    select elements;