使用命名空间读/写XmlDocument

时间:2011-01-06 13:55:13

标签: .net xml vb.net xml-namespaces

考虑以下XmlDocument命名空间:

<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
  <DataSources>
    <DataSource Name="DummyDataSource">
      <rd:DataSourceID>a0a7ff0a-a268-4f7e-b949-9427e308468a</rd:DataSourceID>
      <ConnectionProperties>
        <DataProvider>SQL</DataProvider>
        <ConnectString />
      </ConnectionProperties>
    </DataSource>
  </DataSources>
</Report>

我写道,

Dim doc As New XmlDocument
doc.Load("c:\MyXml.xml")
Dim nsm As New XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition")
nsm.AddNamespace("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")
Dim xnd As XmlNode = doc.SelectSingleNode("//DataSources/DataSource/...", nsm)
MessageBox.Show(xnd.Name)

我想读取和修改以下标记(XPath)的值:

  1. //DataSources/DataSource/rd:DataSourceID
  2. //DataSources/DataSource/ConnectionProperties/DataProvider

2 个答案:

答案 0 :(得分:0)

我的偏好是使用LINQ to XML,然后使用适当的XName而不是字符串读取元素。类似的东西:

Dim defaultSpace As XNamespace = XNamespace.Get("http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition")    
Dim firstSource As XElement = doc.Element(defaultSpace + "DataSources").Element(defaultSpace + "DataSource")

答案 1 :(得分:-1)

你需要使用这些XPath格式并包含namespace-uri() - 这是一个痛苦的问题:

//DataSources[namespace-uri()='']/DataSource[namespace-uri()='']/...