簡體   English   中英

從數據庫導出 XML 文件並在實際列之前獲得沒有任何屬性的干凈格式

[英]Exported XML file from Database and get clean format without any attributes before actual columns

我正在創建一個服務,該服務將從使用 WriteXml 的用戶存儲過程中的 sql server db 生成和導出 xml 文件。 它運行成功,但我不希望輸出 xml 文件在我想要的實際列之前包含任何 xml 屬性。 我試過 IgnoreSchema。 但是第一行 xml 版本仍然存在,我試圖在列之間添加空格。

編碼:

public void TEST(string param)
{    
     List<Model> list = new List<Model>();

     //this function is for access the db and get the data
     DataSet ds = DAL.Function(param);

     //Export as XML File
     //ds.WriteXml(@"C:\Test\Test.XML", XmlWriteMode.WriteSchema);
}

輸出看起來像:

<?xml version = "1.0" standalone="yes"?>
<NewDataSet>
  <Table>
    <a> 005 </a>
    <b> 1 </b>
  </Table>
  <Table>
    <a> 006 </a>
    <b> 2 </b>
  </Table>
</NewDataSet>

但我希望它的格式看起來像這樣:

  <Table>
    <a> 005 </a>
    <b> 1 </b>
  </Table>

  <Table>
    <a> 006 </a>
    <b> 2 </b>
  </Table>

首先,我要指出格式良好的 XML 文檔必須只有一個根元素

在正常情況下,我會說您不應該嘗試弄亂System.Xml命名空間,因為它會變得非常臟。 但是讓我們再想象一下,我們不關心性能和可維護性,當然純粹是作為一個思想實驗。 那么解決您的問題的一種方法是修改XmlWriter使其跳過您的NewDataSet標記:

class MyWriter : XmlTextWriter
{
    private int Top // this is a pointer to top of internal stack that XmlWriter uses to determine closing tag correspondence
    {
        get
        {
            FieldInfo top = typeof(XmlTextWriter).GetField("top", BindingFlags.NonPublic | BindingFlags.Instance);
            return (int)top.GetValue(this);
        }
    }

    public MyWriter(string name, Encoding enc) : base(name, enc) {}

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        if (localName == "NewDataSet") { // skip the tag
            MethodInfo PushStack = typeof(XmlTextWriter).GetMethod("PushStack", BindingFlags.NonPublic | BindingFlags.Instance);
            PushStack.Invoke(this, new object[] {}); // for internal state tracking to work, we still need to push the stack as if we wrote it out. we'll have to account for that later
            return;
        }

        base.WriteStartElement(prefix, localName, ns);
    }

    public override void WriteEndElement()
    {
        if(Top <= 1) return; // do not attempt to write outermost tag, we already skipped it in the opening counterpart
        base.WriteEndElement();
    }
}
void Main()
{
    //...your code here

    var writer = new MyWriter(@"C:\Test\Test.XML", Encoding.UTF8); // instantiate your own writerm
    ds.WriteXml(writer, XmlWriteMode.IgnoreSchema); // and use it instead of stock standard
}

如您所見,問題是, XmlWriter沒有公開一些使其工作所需的方法和屬性,因此我不得不使用反射來調用它們。 此外,通過將某些數據結構保留在類內部(作為練習,嘗試使用上述技術獲取TagInfo[] stack字段,看看會發生什么),它使得獲取某些數據結構變得極其困難。

然而,這應該給你你想要的輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM