在VB.NET中将字符串转换为XML节点

时间:2015-07-20 14:37:44

标签: asp.net xml vb.net

我在数据库列中有一个像这样的

的XML字符串
<trueFalseQuestion id="585" status="correct" maxPoints="10" 
                   maxAttempts="1" 
                   awardedPoints="10" 
                   usedAttempts="1" 
                   xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults">
    <direction>You have NO control over how you treat customers.</direction>
    <answers correctAnswerIndex="1" userAnswerIndex="1">
        <answer>True</answer>
        <answer>False</answer>
    </answers>
</trueFalseQuestion>

但我需要对此字符串执行XML操作,例如选择其名称,属性值,内部文本等。如何从此字符串中实现此操作

修改

我分享了我尝试的代码片段,但没有工作

        Dim myXML As String
        Dim gDt As New DataTable
        gDt.Columns.Add("id")
        gDt.Columns.Add("questionid")
        gDt.Columns.Add("serial")
        gDt.Columns.Add("direction")
        Dim dr As DataRow


            myXML ='<my above shared XML>'
            Dim xmlDoc As New XmlDocument
            xmlDoc.LoadXml(myXML)
            dr = gDt.NewRow
            dr("serial") = 1
            dr("id") = xmlDoc.Attributes("id").Value
            dr("direction") = xmlDoc("direction").InnerText
             gDt.Rows.Add(dr)

但那根本不能正常工作

1 个答案:

答案 0 :(得分:3)

有许多方法可以在.NET中解析XML,例如使用其中一个序列化类或XmlReader类,但最常用的两个选项是使用XElementXmlDocument。例如:

Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim element As XElement = XElement.Parse(input)
Dim id As String = element.@id

或者:

Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim doc As New XmlDocument()
doc.LoadXml(input)
Dim nsmgr As New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("q", "http://www.ispringsolutions.com/ispring/quizbuilder/quizresults")
Dim id As String = doc.SelectSingleNode("/q:trueFalseQuestion/@id", nsmgr).InnerText

根据您更新的问题,您遇到的麻烦就是您没有正确指定命名空间。如果使用XElement,它会更宽容(即松散),但是当您使用XPath选择XmlDocument中的节点时,您需要指定每个命名空间,即使它是顶部的默认命名空间文档的-level元素。