【问题标题】:XmlDocument from XML string that contains custom namespaces causes XmlException?来自包含自定义命名空间的 XML 字符串的 XmlDocument 会导致 XmlException?
【发布时间】:2012-11-02 08:39:38
【问题描述】:

我需要创建一个 XmlDocument 部分通过使用旧的 XML,部分通过创建新的。问题是旧的 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 后,我​​将其打印出来,根据架构对其进行验证,然后将其推送给用户查看。

【问题讨论】:

  • 如果这似乎是同时从现有和新来源创建 XML 的不好方法,我也愿意接受有关以不同方式执行此操作的建议!
  • 有什么异常?并发布(一部分)所需的 XML。
  • 你可以使用 Xlinq (XElement) 吗?可以使用 Xml 和 esp。命名空间更容易。
  • 已编辑以添加更多详细信息。 Henk,我可以在 .net 4 中使用任何东西,并且也愿意使用 Linq。
  • 当尝试使用 Linq to XML(就像你的旧答案一样)并用 body.ReplaceAll(XElement.Parse(topicRevision.Body)); 替换异常抛出行时,我得到了同样的异常。解析我的旧传入 XML 的解析器显然对我的命名空间感到困惑,但我不知道如何解决这个问题。

标签: c# .net xml-parsing xml-namespaces xmlexception


【解决方案1】:

以下是我能想到的最好的解决方法:

 XNamespace  my = "http://foobar.com/";

 var doc = new XDocument(new XElement("root", 
                new XAttribute(XNamespace.Xmlns +  "my", my)));

 var body = new XElement("body");
 doc.Root.Add(new XElement("item", new XAttribute("id", 12345), body));

 string innerItem = @"<aaa><bbb my:attr=""55"">Foo</bbb></aaa>";       
 string itemWrap = @"<wrap xmlns:my=""http://foobar.com/"">" + innerItem + "</wrap>";

 XElement item = XElement.Parse(itemWrap);
 body.Add(item.Element("aaa"));

 Console.WriteLine(doc);

【讨论】:

  • 谢谢,我对这个解决方法很满意。我会和源生成方谈谈,看看我们能否解决更深层次的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 2010-11-11
  • 2014-06-10
  • 2016-06-22
  • 1970-01-01
相关资源
最近更新 更多