如何获取全局声明的xml命名空间

时间:2015-01-28 11:20:50

标签: c# xml xml-namespaces

我遇到了在元素中获取多个名称空间声明的问题,而不是在中央全局位置。原因是我正在使用命名空间创建XElements,然后将其添加到根元素。有一种简单的方法可以避免这种情况吗?这是一个简化的代码示例:

    private void testcode()
    {
        XNamespace ns_xsi = "http://www.w3.org/2001/XMLSchema-instance";
        XNamespace ns_xsd = "http://www.w3.org/2001/XMLSchema";
        XNamespace ns = "InstrumentMeasurement";

        // top-level element
        XElement XResults = new XElement(ns + "Results");

        // this will happen many times
        for(int i = 0; i<3; i++)
        {
            XElement XResult =
                new XElement(ns + "Result",
                    new XAttribute(ns_xsi + "nil", true));
            XResults.Add(XResult);
        }

        // complete the XDoc and write to file
        XDocument XReport = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
        XReport.Add(XResults);
        string strContent = XReport.Declaration.ToString() + Environment.NewLine + XReport;
        System.IO.File.WriteAllText(@"c:\temp\doc.xml", strContent);
        Console.WriteLine(@"written testfile c:\temp\doc.xml");
        return;
    }

以下是生成的xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Results xmlns="InstrumentMeasurement">
  <Result p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
  <Result p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
  <Result p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
</Results>

而不是更清晰的期望版本:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Results xmlns="InstrumentMeasurement
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Result xsi:nil="true" />
  <Result xsi:nil="true" />
  <Result xsi:nil="true" />
</Results>

(顺便说一句,该属性不是垃圾,正如我首先想到的那样,例如, http://www.w3.org/TR/xmlschema-1/#xsi_nil

1 个答案:

答案 0 :(得分:0)

好的,我自己在C#3.0中找到了答案(RTFM)(J + B Albahari,O&#39; Reilly,第3版,2007年,第386页,谷歌图书和其他网站免费)。

&#34;在编写XML之前提示序列化程序:&#34;

XResults.SetAttributeValue(XNamespace.Xmlns + "xsi", ns_xsi);
XResults.SetAttributeValue(XNamespace.Xmlns + "xsd", ns_xsd);

这不仅解决了我原来的问题,而且还解决了如何添加未引用但仍然需要我的项目所需的命名空间声明。

现在好的,理想的输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
        xmlns="InstrumentMeasurement">
  <Result xsi:nil="true" />
  <Result xsi:nil="true" />
  <Result xsi:nil="true" />
</Results>
相关问题