我有一个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)
};
}
Using 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);
}
}
}