【问题标题】:VB 2010 XML files with namespaces are causing trouble带有命名空间的 VB 2010 XML 文件引起了麻烦
【发布时间】:2017-03-31 22:28:20
【问题描述】:

我正在尝试使用 LINQ (XDocument) 解析出一个 XML 文件,并且文档中有一个命名空间会搞砸一切。

我发现this SO question about the same thing 影响了元素名称,但我已经解决了(使用Name.LocalName 属性)。但它会导致其他函数出现相同的问题,例如获取具有特定名称的元素。例如:

XML 代码简介:

<FeatureDefinitions xmlns="http://website.com/schema/features">
    <FeatureDefinition  Name="FeatureOne" >
      <Attributes>
        <ListAttribute Name="TYPE" Description="MATERIAL USED.">
          <ListItems>
            <Item>Material 1</Item>
            <Item>Material 2</Item>
            <Item>OTHER </Item>
          </ListItems>
        </ListAttribute>
        <ListAttribute Name="POSITION">
          <ListItems>
            <Item>BEGIN</Item>
            <Item>EDGE</Item>
            <Item>END</Item>
            <Item>TOE</Item>
            <Item>TOP</Item>
          </ListItems>
        </ListAttribute>
        <StringAttribute Name="NOTES" />
      </Attributes>
    </FeatureDefinition>
</FeatureDefinitions>

然后在代码中:

Dim nodeFeatureDef as XElement = nodeFeatureDefinitions.Element("Attributes")

所以,现在发生的情况是,当名称空间包含在 XML 的第一行中时,我无法获得 element("Attributes") 及其关联节点。但是如果我删除第一行中的命名空间属性,它就可以正常工作了。

很多论坛都建议VB源代码导入命名空间,但我不能确定这个进程的每个文件都会有相同的命名空间。它通过使用 Name.LocalName 属性到 Name 属性来工作,但我不知道如何对 Elements 属性做同样的事情。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: xml vb.net linq namespaces


    【解决方案1】:

    如果命名空间未知,可以从根元素中获取:

    Dim xml As XDocument = ...
    Dim ns = xml.Root.Name.Namespace
    

    然后您可以使用XNamespace.GetName 方法创建一个限定名称,例如

    Dim attrs = xml.Descendants(ns.GetName("ListAttribute"))
    

    如果根元素上没有命名空间,这也应该可以正常工作。

    【讨论】:

    • 我想我们赢了!对我的应用程序的代码结构稍作修改,到目前为止它似乎做得很完美。谢谢!
    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2011-11-07
    • 2011-01-05
    • 2013-06-07
    • 2014-01-30
    相关资源
    最近更新 更多