我试图将多年前在VB6中创建的这个函数转换为C#,但我不知道如何去做。在这个VB6代码中,我对如何在{C#中使用MSXML2.DOMDocument40
作为参数感到困惑。我确定它会要求使用XmlDocument
。
Private Function m_LoadXML(xmlDoc As MSXML2.DOMDocument40, xmlRoot As MSXML2.IXMLDOMElement, strXMLScript As String) As Boolean
On Error GoTo Proc_Error
Dim blnResult As Boolean
Dim strMsg As String
blnResult = False
Set xmlDoc = New MSXML2.DOMDocument40
If xmlDoc.Load(strXMLScript) Then
Set xmlRoot = SafeElementNode(xmlDoc, mcstrXmlNodeRoot)
If Not xmlRoot Is Nothing Then
blnResult = True
Else
strMsg = "Invalid XML database definition file " & strXMLScript
RaiseEvent ErrorMessage(strMsg)
End If
Else
strMsg = "Can not load XML database definition file " & strXMLScript
RaiseEvent ErrorMessage(strMsg)
End If
Proc_Exit:
On Error Resume Next
m_LoadXML = blnResult
Exit Function
Proc_Error:
RaiseEvent ErrorMessage(Error)
Resume Proc_Exit
End Function
Public Function SafeElementNode( _
vxmlDocumentOrElement As MSXML2.IXMLDOMNode, _
vstrQueryString As String _
) As MSXML2.IXMLDOMNode
On Error Resume Next
Set SafeElementNode =
vxmlDocumentOrElement.selectSingleNode(vstrQueryString)
End Function
以下是我到目前为止所提出的:
private bool m_LoadXML(XmlElement xmlRoot, string strXMLScript)
{
bool blnResult = false;
string strMsg;
var xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(strXMLScript);
xmlRoot = xmlDoc.DocumentElement;
if (xmlRoot != null) blnResult = true;
else
{
strMsg = "Invalid XML database definition file " + strXMLScript;
MessageBox.Show(strMsg);
}
}
catch (Exception)
{
strMsg = "Can not load XML database definition file " + strXMLScript;
MessageBox.Show(strMsg);
throw;
}
return blnResult;
}
答案 0 :(得分:0)
我认为这应该有用。您拥有的现有代码并未将xmlRoot变量声明为out参数,因此您最终会得到一个空根元素。
private bool m_LoadXML(out XmlElement xmlRoot, string strXMLScript)
{
bool blnResult = false;
string strMsg;
var xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(strXMLScript);
xmlRoot = xmlDoc.DocumentElement;
if (xmlRoot != null) blnResult = true;
else
{
strMsg = "Invalid XML database definition file " + strXMLScript;
MessageBox.Show(strMsg);
}
}
catch (Exception)
{
strMsg = "Can not load XML database definition file " + strXMLScript;
MessageBox.Show(strMsg);
throw;
}
return blnResult;
}
private void TestLoadXml(string xmlFile)
{
XmlElement elem;
var result = m_LoadXML(out elem, xmlFile);
}
与其他评论员所说的一样,XDocument非常适合使用,值得一试。