0

我试图在我的函数中为 parentElement 赋值

这是功能

Private Shared Function AddDynamicChildElement(parentElement As XmlElement, url As [String], title As [String], description As [String]) As XmlElement
    ' Create new element from the parameters
    Dim childElement As XmlElement = parentElement.OwnerDocument.CreateElement(SiteMapNodeName)
    childElement.SetAttribute("url", url)
    childElement.SetAttribute("title", title)
    childElement.SetAttribute("description", description)

    ' Add it to the parent
    parentElement.AppendChild(childElement)
    Return childElement
End Function

我像这样在我的 Page_Load 中调用了 AddDynamicChildElement

AddDynamicChildElement(root,"Home.aspx","Home","This is Home Page")

我需要将价值赋予我的“根”。我从用户输入中获得了 root 的值,它是 String,所以我需要将它转换为 XmlElement

这是我的代码

Private Function header_pointing(strRoot As String) As XmlElement
    Dim doc As XmlDocument = New XmlDocument()

    If strRoot = "STANDARD" Then
        doc.LoadXml("General Preference")
    ElseIf strRoot = "PA" Then
        doc.LoadXml("Personal Administration")
    ElseIf strRoot = "TA" Then
        doc.LoadXml("Time Attendance & Leave Administration")
    ElseIf strRoot = "PG" Then
        doc.LoadXml("Personal Government")
    ElseIf strRoot = "PY" Then
        doc.LoadXml("Payroll Administration")
    ElseIf strRoot = "RC" Then
        doc.LoadXml("Recruitment Management")
    ElseIf strRoot = "PF" Then
        doc.LoadXml("Performance Management")
    ElseIf strRoot = "LO" Then
        doc.LoadXml("Load Administration")
    ElseIf strRoot = "MD" Then
        doc.LoadXml("Medical Administration")
    ElseIf strRoot = "RE" Then
        doc.LoadXml("Reimbursement Administration")
    ElseIf strRoot = "LD" Then
        doc.LoadXml("Learning And Development Management")
    ElseIf strRoot = "CT" Then
        doc.LoadXml("Catering Administration")
    ElseIf strRoot = "CR" Then
        doc.LoadXml("Custom Report")
    ElseIf strRoot = "SRR" Then
        doc.LoadXml("Special Request Report")
    ElseIf strRoot = "TOOLS" Then
        doc.LoadXml("Tools")
    Else
        doc.LoadXml(strRoot)
    End If

    Return doc.DocumentElement
End Function

当我运行此代码时,它会引发错误

这是错误

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

它指向我的代码的最后一行

有什么建议是什么原因以及如何纠正它?

感谢所有帮助/建议

4

1 回答 1

0

假设我已经了解您要执行的操作(即更改根元素的名称),请尝试此操作。

它要求您用返回对象覆盖现有XmlDocument对象:

Private Function header_pointing(doc as XmlDocument, strRoot As String) As XmlDocument
    Dim elName as string = ""
    Select Case strRoot
        Case "STANDARD"
            elName = "GeneralPreference"
        Case "PA"
            elName = "PersonalAdministration"
        ...
        Case Else
            elName = strRoot.Replace(" ","")
    End Select

    Dim newDoc as New XmlDocument()
    Dim newRoot as XmlElement = docNew.CreateElement(elName)
    newDoc.AppendChild(newRoot)
    newRoot.InnerXml = doc.DocumentElement.InnerXml
    Return newDoc
End Function
于 2013-09-18T07:58:24.840 回答