我有一个名为 app.exe.config 的 .config 文件,我想在其中更新端点标签中存在的名为地址的特定属性值。我尝试了下面的代码,但无法得到什么问题。我是 vb.net 的新手.请帮忙.
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup>
<system.serviceModel>
<client>
<endpoint address="valuetobeupdated"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_CompassSMSService"
contract="CompassSMSService.CompassSMSService" name="BasicHttpBinding_CompassSMSService" />
</client>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_CompassSMSService" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
我使用了以下代码,但它失败了
Dim str As String = "Demo"
Dim doc As XmlDocument = New XmlDocument()
doc.Load("C:Userse554DesktopPACapp.exe.config")
'Dim formId As XmlAttribute
For Each Attribute As XmlAttribute In doc.DocumentElement.Attributes
MessageBox.Show(Attribute.Value)
Next
您可以使用 XPath 语法获取端点元素的地址属性,例如:
Dim str As String = "Demo"
Dim doc As XmlDocument = New XmlDocument()
doc.Load("C:Userse554DesktopPACapp.exe.config")
Dim endpoint = doc.SelectSingleNode("configurationsystem.serviceModelclientendpoint")
Dim address = endpoint.Attributes["address"].Value;
MessageBox.Show(address)
请注意,SelectSingleNode
将获取函数参数中提供的第一个节点匹配的 XPath 字符串。看到 XPath 直观易用,此示例演示了 XPath 字符串来表示从根元素 ( <configuration>
) 到<endpoint>
元素(地址属性所在的位置)的路径。
这里有几点:
.XML:
DocumentElement
是文档中的顶级元素,因此在本例中为 configuration
.所以DocumentElement.Attributes
顶级的属性。
因此,如果您的 xml 看起来像这样:
<configuration foo="bar">
...
</configuration>
然后DocumentElement.Attributes
会找到foo
属性。
WCF 绑定
我假设您在这里尝试的是动态设置客户端的端点以指向所需的服务器。如果是这样的话,那么这不是真正的方法。
最好通过在代码中动态创建和连接到终结点来执行此操作。
这个答案很好地涵盖了这一点(在 C# 中,但原理是相同的)。
也许这会起作用:
Dim XmlDoc As New XmlDocument()
Dim file As New StreamReader(filePath)
XmlDoc.Load(file)
For Each Element As XmlElement In XmlDoc.DocumentElement
If Element.Name = "system.service" Then
For Each Element2 As XmlElement In Element
If Element2.Name = "client" Then
For Each Element3 As XmlElement In Element2
For Each Node As XmlNode In Element3.ChildNodes
Node.Attributes(0).Value = YourNewAddress
Next
Next
End If
Next
End If
Next
file.Dispose()
file.Close()
Dim save As New StreamWriter(filePath)
XmlDoc.Save(save)
save.Dispose()
save.Close()