如何将GML字符串转换为XML?

时间:2018-10-15 20:42:32

标签: c# xml xml-namespaces

我有一个GML字符串:

<gml:LineString><gml:coordinates>1537544.53,452064.2 1537541.719999999,452062.3099999999 1537523.159999999,452044.55 1537544.53,452064.2</gml:coordinates></gml:LineString>

现在我想将其转换为xml文档

var t = "<gml:LineString>....</gml:LineString>";
XmlDocument doc = new XmlDocument();
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
doc.Load(t);

但是在doc.Load(t);上出现了异常:

System.Xml.XmlException: "Prefix "gml" undeclared."

如何添加名称空间和读取读取行?

更新 我会根据@jdweng答案修复代码:

XmlReaderSettings settings = new XmlReaderSettings { NameTable = new NameTable() };
var nsmgr = new XmlNamespaceManager(settings.NameTable);
nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
XmlParserContext context = new XmlParserContext(null, nsmgr, "", XmlSpace.Default);

XmlReader reader = XmlReader.Create(new StringReader(gmlString), settings, context);

 if (gmlString.StartsWith("<gml:Polygon>"))
 {
     XmlSerializer serializer = new XmlSerializer(typeof(PolygonType));
     return new tGeoLPT { Item = (PolygonType)serializer.Deserialize(reader) 
   };
 }

1 个答案:

答案 0 :(得分:1)

使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string coordinates = "1537544.53,452064.2 1537541.719999999,452062.3099999999 1537523.159999999,452044.55 1537544.53,452064.2";
            string line = "<gml:LineString  xmlns:gml=\"http://www.opengis.net/gml\"></gml:LineString>";
            XElement xLine = XElement.Parse(line);
            XNamespace ns = xLine.GetNamespaceOfPrefix("gml");
            xLine.Add(new XElement(ns + "coordinates"), coordinates);
        }
    }
}