Linq to XML XElement解析未知命名空间
问题描述:
我有一个XML文档。例如:Linq to XML XElement解析未知命名空间
<Root xmlns:x="anynamespace" xmlns:html="htmlnamespace">
<x:Data>bla bla</x:Data>
</Root>
这里我得到了html命名空间来格式化数据。元素的BUT值可以是例如<html:Font ...>bla bla</html:Font>
或bla <html:Font ...>bla</htmk:Font>
在我的C#代码我这样做:new XElement(main + "Data",myvalue); //main is namespace
结果我得到了<x:Data><html:Font ...>bla bla etc.
Linq的替代关键变量与他们的文本代码。所以这是不可接受的。
然后我试过这个:new XElement(main + "Data",XElement.Parse(myvalue));
在那里我得到了前缀html无法识别的异常。
有没有人遇到过这样的问题?你是如何解决这个问题的?
答
通常,您不会构造字符串中的内容,而只是使用LINQ to XML构造节点,例如
XElement foo = XElement.Parse(@"<foo xmlns=""http://example.com/ns1"" xmlns:html=""http://example.com/html"">
<bar>bar 1</bar>
</foo>");
foo.Add(new XElement(foo.GetNamespaceOfPrefix("html") + "p", "Test"));
Console.WriteLine(foo);
创建XML
<foo xmlns="http://example.com/ns1" xmlns:html="http://example.com/html">
<bar>bar 1</bar>
<html:p>Test</html:p>
</foo>
如果你想分析给出一个字符串片段,那么也许下面的方法可以帮助:
public static void AddWithContext(this XElement element, string fragment)
{
XmlNameTable nt = new NameTable();
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
IDictionary<string, string> inScopeNamespaces = element.CreateNavigator().GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
foreach (string prefix in inScopeNamespaces.Keys)
{
mgr.AddNamespace(prefix, inScopeNamespaces[prefix]);
}
using (XmlWriter xw = element.CreateWriter())
{
using (StringReader sr = new StringReader(fragment))
{
using (XmlReader xr = XmlReader.Create(sr, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }, new XmlParserContext(nt, mgr, xw.XmlLang, xw.XmlSpace)))
{
xw.WriteNode(xr, false);
}
}
xw.Close();
}
}
}
class Program
{
static void Main()
{
XElement foo = XElement.Parse(@"<foo xmlns=""http://example.com/ns1"" xmlns:html=""http://example.com/html"">
<bar>bar 1</bar>
</foo>");
foo.Add(new XElement(foo.GetNamespaceOfPrefix("html") + "p", "Test"));
Console.WriteLine(foo);
Console.WriteLine();
foo.AddWithContext("<html:p>Test 2.</html:p><bar>bar 2</bar><html:b>Test 3.</html:b>");
foo.Save(Console.Out, SaveOptions.OmitDuplicateNamespaces);
}
这样,我得到
<foo xmlns="http://example.com/ns1" xmlns:html="http://example.com/html">
<bar>bar 1</bar>
<html:p>Test</html:p>
<html:p>Test 2.</html:p>
<bar>bar 2</bar>
<html:b>Test 3.</html:b>
</foo>
+0
嗯..感谢,有帮助。) – StNickolas 2012-07-31 02:30:23
是你的关于命名空间或关于encodin的问题g HTML? – 2012-07-30 06:32:12
@亨克Holterman,我的问题是...我想在我的sql表格中的某些字段有HTML格式。但它可能是,也可能不是,所以我想做一个“xml注入”。 – StNickolas 2012-07-30 06:57:20
对。 'XElement.Parse()'不会从连接的XDoc _before_中获取命名空间。 – 2012-07-30 07:10:22