通常,您不会构造字符串中的内容,而只是使用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>
是你的关于命名空间或关于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