UPDATE - 修改後的代碼可用於任何節點/屬性,其值爲01/01/1900
。
我會在轉換爲JSON之前處理XML文檔。如果您的日期值是節點或屬性值,那麼如何做LinqPad示例如下。因爲我不知道你的XML數據結構與裸簡單的例子:
void Main()
{
// IF IT IS NODE VALUE
var xml = @"<data>
<objectA>
<dateValueA>01/01/1900</dateValueA>
<dateValueB>01/01/1971</dateValueB>
</objectA>
<objectB>
<dateValueA>01/01/2002</dateValueA>
<dateValueB>01/01/1900</dateValueB>
<dateValueZ>01/01/2011</dateValueZ>
</objectB>
<objectC>
<dateValueA>01/01/1910</dateValueA>
<dateValueB>01/01/2012</dateValueB>
<dateValueC>01/01/1900</dateValueC>
</objectC>
</data>";
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var nodes = xmlDoc.SelectNodes("//*[text()='01/01/1900']");
foreach(XmlNode node in nodes)
{
node.InnerText = "01/01/0001";
}
string jSonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true);
"// IF IT IS NODE VALUE - RESULTS".Dump();
jSonString.Dump();
// IF IT IS ATTRIBUTE VALUE
var xmlAttr = @"<data>
<objectA dateValueA='01/01/1900' dateValueB='01/01/1900' dateValueC='01/01/2011' />
<objectB dateValueB='01/01/2011' someOtherDate='01/01/1900' />
<objectC dateValueC='01/01/1900' dontChangeThisDate='05/04/1923' />
</data>";
var xmlDocAttr = new XmlDocument();
xmlDoc.LoadXml(xmlAttr);
var nodesAttr = xmlDoc.SelectNodes("//*[@*='01/01/1900']");
for(var i=0; i < nodesAttr.Count; i++)
{
foreach(XmlAttribute attrib in nodesAttr[i].Attributes)
{
if (attrib.Value == "01/01/1900")
{
attrib.Value = "01/01/0001";
}
}
}
string jSonStringAttr = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true);
"// IF IT IS ATTRIBUTE VALUE - RESULTS".Dump();
jSonStringAttr.Dump();
}
和結果:
// IF IT IS NODE VALUE - RESULTS
{"objectA":{"dateValueA":"01/01/0001","dateValueB":"01/01/1971"},"objectB":{"dateValueA":"01/01/2002","dateValueB":"01/01/0001","dateValueZ":"01/01/2011"},"objectC":{"dateValueA":"01/01/1910","dateValueB":"01/01/2012","dateValueC":"01/01/0001"}}
// IF IT IS ATTRIBUTE VALUE - RESULTS
{"objectA":{"@dateValueA":"01/01/0001","@dateValueB":"01/01/0001","@dateValueC":"01/01/2011"},"objectB":{"@dateValueB":"01/01/2011","@someOtherDate":"01/01/0001"},"objectC":{"@dateValueC":"01/01/0001","@dontChangeThisDate":"05/04/1923"}}
會爲你工作?
這聽起來像數據庫中的一個糟糕的設計開始 - 那些日期列應該爲空來表示沒有日期而不是01/01/1900 - 我會開始糾正它。 –
@TrevorPilley我知道,但空值不允許作爲不能改變的內部策略。添加到問題中。 –