2011-08-30 66 views
1

查询你能帮转换LINQ到XML从VB到C#

Dim ScriptDOC As XDocument 
    ScriptDOC = XDocument.Parse(e.Result) 

Dim Result = From ele In XElement.Parse(ScriptDOC.ToString).Elements("HANDERDETAILS") 
If IsNothing(Result.Descendants("RESULT")) = False Then status = Result.Descendants("RESULT").Value 

If LCase(status) = "ok" Then 
    If IsNothing(Result.Descendants("BRANCHID")) = False Then BranchID = Result.Descendants("BRANCHID").Value 

End If 

从转换器,我得到这个代码:

XDocument ScriptDOC = default(XDocument); 
string status = ""; 

ScriptDOC = XDocument.Parse(e.Result); 

dynamic Result = from ele in XElement.Parse(ScriptDOC.ToString).Elements("HANDERDETAILS"); 
if ((Result.Descendants("RESULT") == null) == false) 
    status = Result.Descendants("RESULT").Value; 

if (Strings.LCase(status) == "ok") { 
    if ((Result.Descendants("BRANCHID") == null) == false) 
     BranchID = Result.Descendants("BRANCHID").Value; 
} 

这是不好的。

这是我的xml:

<AAAAA> 
    <HANDERDETAILS> 
    <RESULT>OK</RESULT> 
    <BRANCHID>4</BRANCHID> 
    <HANDLERID>1</HANDLERID> 
    <HANDLERNAME>some Admin</HANDLERNAME> 
    <BRANCHNAME>Asome New</BRANCHNAME> 
    </HANDERDETAILS> 
</AAAAA> 

回答

2

你用什么转换器?它看起来可以显着改善。您确实需要注意哪些情况下您正在收集一个集合,但是希望您的原始代码看起来没有被处理的单个对象。

XDocument ScriptDOC = XDocument.Parse(e.Result); 

var Result = ScriptDOC.Element("AAAAA").Element("HANDERDETAILS"); 
if (Result.Element("RESULT") != null) 
{ 
    Status = Result.Element("RESULT").Value; 
    if (Status.ToLower() == "ok") 
     if (Result.Element("BRANCHID") != null) 
      BranchID = Result.Element("BRANCHID").Value; 
} 

您还想留意名称空间。在VB中,您可以在类中声明它们为Import,但在C#中,您必须在代码中明确指定它们。

XNamespace ns = "http://www.someuri"; 
var Result = ScriptDOC.Elements(ns + "HANDERDETAILS"); 
+0

'Import'ed命名空间可以在XML Axis属性中使用,但不能在通过调用方法直接使用LINQ to XML时使用。 – svick

+0

不幸的是id不起作用。如果你看看xml我已经添加了 – user278618

+0

好的,你的XML不是以根节点中的HANDERDETAILS开头的,因此Result返回空。将该行更改为'var Result = ScriptDOC.Element(“AAAAA”)。Element(“HANDERDETAILS”);'另外,对Descendants的调用可以更改为Element,并消除.First,因为Element返回找到的第一个,而不是IEnumerable。我编辑了包含这些更改的代码示例。 –