2013-03-27 64 views
0

第一次使用XML並且可以通過XML進行迭代我很難找出將元素轉換爲.Net對象的最佳方法。具體而言,我需要獲得構成簡化地圖的點。如何將XML元素轉換爲.Net對象

Imports System 
Imports System.Xml 
Imports System.Xml.XPath 
Imports System.Linq 
Imports System.Xml.Linq 

Module Module1 

    Dim s As XDocument = 
<?xml version="1.0" encoding="UTF-8"?> 
<map:Map xmlns="java:com.raytheon.atc.chi.graphics.geom2d" xmlns:map="java:com.raytheon.atc.chi.adt.map" unit="m" lat="41.975953650" lon="-87.903248430" alt="78.33"><!--ASDE-X DP map for facility:ord Created 10/20/2009 2:22:31 PM--> 
    <map:Layer isVisible="true"><map:Line type="Runway"></map:Line> 
     <map:Region type="Runway"><Surface operation="union"> 
      <Polygon><Point x="1618.87" y="-742.10"></Point> 
       <Point x="1459.74" y="-742.52"></Point> 
       <Point x="1058.11" y="-743.35"></Point> 
      </Polygon> 
      <Polygon><Point x="16.82" y="1760.35"></Point> 
       <Point x="46.31" y="1725.16"></Point> 
       <Point x="16.82" y="1760.35"></Point> 
      </Polygon> 
      <Polygon><Point x="16.82" y="1760.35"></Point> 
       <Point x="16.82" y="1760.35"></Point> 
      </Polygon> 
      </Surface> 
     </map:Region> 
    </map:Layer> 
</map:Map> 


    Public Sub Parse() 

     Dim ns As New XmlNamespaceManager(New NameTable()) 

     ns.AddNamespace("x", "java:com.raytheon.atc.chi.graphics.geom2d") 
     ns.AddNamespace("m", "java:com.raytheon.atc.chi.adt.map") 

     Debug.Print("Points:") 
     Dim elements = s.XPathSelectElements("//m:*//m:Region/x:Surface/x:Polygon/x:Point", ns) 
     For Each element As XElement In elements 
      'Convert this element to a System.Windows.Point 
     Next 
    End Sub 

End Module 
+0

對不起,我不知道如何將其在VB.net編碼。但在C#中,我使用Linq來解析文檔並根據它加載變量。您也可以考慮使用XmlSerializer將數據反序列化到您的類中。 – cgatian 2013-03-27 11:55:54

回答

1
Dim points = s.XPathSelectElements("//m:*//m:Region/x:Surface/x:Polygon/x:Point", ns).Select(function(e) new Point(CDbl(e.Attribute("x")), CDbl(e.Attribute("y")))).ToList() 

或使用For Each方法:

For Each element As XElement In elements 
    Dim p As new Point(CDbl(element.Attribute("x")), CDbl(element.Attribute("y"))) 
Next 
+0

謝謝,效果很好。我不得不在「X」和「Y」部分加上「」,但除此之外就是這樣。 – user38349 2013-03-27 12:04:55