无法将“System.Xml.XmlComment”类型的对象强制转换为“System.Xml.XmlElement”类型

时间:2016-08-17 07:05:41

标签: xml vb.net console-application

我正在尝试在控制台应用程序的app.config中更新连接字符串用户ID和密码。我明白了:

  

无法将“System.Xml.XmlComment”类型的对象强制转换为类型   'System.Xml.XmlElement'

使用以下代码。粗体字表示错误发生的位置。

Dim XmlDoc As New XmlDocument()
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
 **For Each xElement As XmlElement In XmlDoc.DocumentElement**
     If xElement.Name = "connectionStrings" Then
         Dim conStringBuilder As New SqlConnectionStringBuilder(sConnectionString)
          conStringBuilder.UserID = sNewUserID
           conStringBuilder.Password = sNewPwd
           xElement.FirstChild.Attributes(2).Value = conStringBuilder.ToString()
     End If
 Next

XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

2 个答案:

答案 0 :(得分:0)

您可以在XmlElement上使用Name属性之前进行类型检查。我认为以下代码应达到您的目的:

VB .Net:

For Each element In XmlDoc.DocumentElement
    If element.GetType.Equals(GetType(System.Xml.XmlElement)) Then //Type check first
        Dim xElement As XmlElement = CType(element,XmlElement) //Then convert to XmlElement
        If (xElement.Name = "connectionStrings") Then
            Dim conStringBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder(sConnectionString)
            conStringBuilder.UserID = sNewUserID
            conStringBuilder.Password = sNewPwd
            xElement.FirstChild.Attributes(2).Value = conStringBuilder.ToString
        End If            
    End If        
Next

C#:

    foreach (var element in XmlDoc.DocumentElement)
    {
        if (element.GetType().Equals(typeof(System.Xml.XmlElement)))  //Type check first
        {
            XmlElement xElement = (XmlElement)element;   //Then convert to XmlElement

            if ((xElement.Name == "connectionStrings"))
            {
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(sConnectionString);
                conStringBuilder.UserID = sNewUserID;
                conStringBuilder.Password = sNewPwd;
                xElement.FirstChild.Attributes[2].Value = conStringBuilder.ToString();
            }
        }
    }

答案 1 :(得分:-3)

foreach (XmlLinkedNode xe in xn.ChildNodes){
  if (xe.NodeType != XmlNodeType.Comment){

  }
}