如何将XML元素转换为.Net对象

时间:2013-03-27 11:51:32

标签: xml vb.net xml-parsing xsd

第一次使用XML并且我可以迭代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

1 个答案:

答案 0 :(得分: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