我一直在Scott Allen的Puralsight course on Linq Fundamentals工作,这个链接部分描述了使用命名空间前缀读取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 :(得分: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");
答案 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;