【问题标题】:Resolve namespaces in XDocument c#在 XDocument c# 中解析命名空间
【发布时间】:2011-11-16 16:51:47
【问题描述】:

我正在从一个包含几个命名空间的 XML 文件中导入一些数据。我正在使用嵌套类来导入不同级别的数据。不幸的是,我无法访问内部类中的数据。我知道问题与命名空间有关,但我不知道如何在不修改内部类的情况下解决它们。有谁知道我如何解析 XDocument 中的命名空间。

这是该 XML 的一部分:

<TransXChange xmlns="http://www.transxchange.org.uk/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:apd="http://www.govtalk.gov.uk/people/AddressAndPersonalDetails" 
xsi:schemaLocation="http://www.transxchange.org.uk/ http://www.transxchange.org.uk/schema/2.1/TransXChange_registration.xsd" 
xml:lang="en" CreationDateTime="2004-06-09T14:20:00-05:00" 
>
    <Operators>
        <LicensedOperator id="O1" >
            <NationalOperatorCode>ABC</NationalOperatorCode>
            <OperatorAddresses>
                <CorrespondenceAddress>
                    <apd:Line>45 City Road</apd:Line>
                </CorrespondenceAddress>
            </OperatorAddresses>
        </LicensedOperator>
    </Operators>
</TransXChange>

【问题讨论】:

  • 在 SO 上的简单搜索应该已经向您展示了解决方案

标签: c# namespaces linq-to-xml


【解决方案1】:

您必须使用与 XML 中使用的名称匹配的名称空间,对于 Linq to XML,您可以使用 XNamespace,即:

XDocument doc = XDocument.Load("test.xml");
XNamespace apd = "http://www.govtalk.gov.uk/people/AddressAndPersonalDetails";
var firstHit = doc.Descendants(apd + "Line").First();

【讨论】:

    【解决方案2】:

    你需要告诉解析器如何引用命名空间:

    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlElem.OwnerDocument.NameTable);
    nsmgr.AddNamespace("apd", "http://[PATH_TO_NAMESPACE_DOC]");
    

    应该这样做

    【讨论】:

    • 我想知道是否有任何方法可以解析 XDocumet 中的名称空间:XDocument doc = new XDocument(); doc = XDocument.Load(文件名);
    • 我不知道。使用XmlNamespaceManager有问题吗?
    • 不幸的是,我有 40 多个类,在所有这些类中我都使用了 XDocument、xml linq,而不是 XML Document
    猜你喜欢
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2011-11-15
    • 1970-01-01
    • 2019-07-09
    相关资源
    最近更新 更多