通常您不会从字符串构造内容,而是简单地使用 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>