一部は古いXMLを使用し、一部は新しいXMLを作成してXmlDocumentを作成する必要があります。問題は、古いXMLにカスタム名前空間が含まれていて、XmlExceptionが発生したため、それらを使用できないように見えることです。名前空間をさまざまな場所に追加しようとしましたが、例外を乗り越えることができません。
例外
System.Xml.XmlException was unhandled by user code
Message='my' is an undeclared prefix. Line 1, position 42.
Source=System.Xml
私のコード
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("my", "http://foobar.com/");
doc.Schemas.Add(schema);
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("root");
root.SetAttribute("xmlns:my", "http://foobar.com/");
doc.AppendChild(root);
foreach (var item in GetItems())
{
XmlElement elem = doc.CreateElement("item");
elem.SetAttribute("id", item.id);
// Append body to elem
XmlElement body = doc.CreateElement("body");
body.InnerXml = item.Body; // Here is where I get the exception
elem.AppendChild(body);
// Append elem to root
root.AppendChild(elem);
}
Item.Bodyからの入力はに似ています
<aaa><bbb my:attr="55">Foo</bbb></aaa>
出力は次のようになると思いました
<?xml version="1.0" encoding="utf-8"?>
<root my:attr="http://foobar.com/">
<item id="12345">
<body>
<aaa>
<bbb my:attr="55">Foo</bbb>
</aaa>
</body>
</item>
</root>
私はこの方法を使用する代わりの方法を受け入れています。XmlDocumentを作成したら、それをきれいに印刷し、スキーマに対して検証してから、ユーザーが表示できるようにプッシュします。