일반적으로 문자열로 내용을 구성하지 않고 LINQ to XML을 사용하여 간단하게 노드를 구성합니다.
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>
을 얻을 방법을 : 당신은 문자열로 주어진 조각을 구문 분석하려면
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>
를 생성
네임 스페이스 또는 encodin에 관한 문제가 있습니까? g HTML? –
@Henk Holterman, 제 문제는 ... 일부 필드의 SQL 테이블에 html 서식이 있어야합니다. 하지만 그럴 수도 있고 그렇지 않을 수도 있습니다. 그래서 나는 "xml injection"과 같은 일을하고 싶습니다. – StNickolas
오른쪽. XElement.Parse()가 첨부되기 전에 XDoc에서 네임 스페이스를 가져올 방법이 없습니다. –