如何使用linq to xml读取属性值

时间:2016-07-28 18:55:23

标签: xml vb.net winforms linq

这里我使用的是xml文件。文件名是KMMiddleTier.xml

    <?xml version="1.0" encoding="utf-8"  standalone ="yes" ?>
<KMMiddleTierSecurity>
  <ConnectionKeys>
    <ConnectionKey Key="DB_DEV" ConnectionString="Data source=TTDJS;Persist Security Info=False;Initial Catalog=TAMSdev;User Id={0};Password={1};"  timeout="200" UserPasswordKey="DBUser"/>
    <ConnectionKey Key="DB_QA"  ConnectionString="Data source=YYSHDJ;Persist Security Info=False;Initial Catalog=TAMSqa;User Id={0};Password={1};"  timeout="200" UserPasswordKey="DBUser"/>
    <ConnectionKey Key="DB_PROD" ConnectionString="Data source=JSUDHS;Persist Security Info=False;Initial Catalog=TAMSDB;User Id={0};Password={1};"  timeout="200" UserPasswordKey="DBUser"/>
    <ConnectionKey Key="KMAUDIT" ConnectionString="data source=DISIS;FailOver Partner=LKWSQLTESTWS\LKWSQLTEST;Persist Security Info=False;Initial Catalog=KMAuditDEV;User Id={0};Password={1};Application Name='MiddleTier';Workstation ID='Thotsrc1'"  UserPasswordKey="KMAuditUser"/>
  </ConnectionKeys>
</KMMiddleTierSecurity>

我在使用vb.net的Windows窗体中使用

我想知道如何将“DB_DEV”键连接字符串值检索到变量中。

请建议一些代码

我希望某些变量的结果为"Data source=TTDJS;Persist Security Info=False;Initial Catalog=TAMSdev;User Id={0};Password={1};"

1 个答案:

答案 0 :(得分:0)

您可以使用@attrname语法来引用属性,因此:

Dim conStr = (
    From e In xml.<KMMiddleTierSecurity>.<ConnectionKeys>.<ConnectionKey>
    Where e.@Key = "DB_DEV"
    Select e.@ConnectionString
).Single()
Console.WriteLine(conStr)
  

数据源= TTDJS;持久安全信息=假;初始目录= TAMSdev;用户ID = {0};密码= {1};