[英]Splitting out value from Child XElement when it exceeds in Length
當值超過設置的長度時,我試圖從子XElement
拆分出值,因為這在保存值時會引起問題。
因此,以下是出現問題的示例
<ParentNode>
<ChildNode>This is an example value</ChildNode>
<ChildNode />
<ChildNode />
</ParentNode>
由於數據庫中的長度限制,以上內容導致錯誤
String or binary data would be truncated.
因此,為防止發生這種情況,我嘗試從適用限制的位置拆分值,並將其放入以下子節點,如下所示:
<ParentNode>
<ChildNode>This is an</ChildNode>
<ChildNode>example value</ChildNode>
<ChildNode />
</ParentNode>
到目前為止,我一直在嘗試訪問子元素內的值,但是不確定是否通過創建新的XElement
拆分值?
foreach (XElement childnode in xElement.Elements("ChildNode"))
{
// Check the length of the value and if it exceeds then split it into
// child nodes
if (childnode.Value.Length > 80)
{
}
}
有人引導我朝正確的方向前進嗎?
這是循環遍歷子節點時的一種方法:
int maxLength = 10;
foreach (XElement childnode in xElement.Elements("ChildNode"))
{
// Check the length of the value and if it exceeds then split it into
// child nodes
if (childnode.Value.Length > maxLength)
{
XElement xE = new XElement("ChildNode", childnode.Value.Substring(maxLength).Trim());
childnode.Value = childnode.Value.Substring(0, maxLength);
childnode.AddAfterSelf(xE);
}
}
我已經嘗試過,並且在調用Console.WriteLine(doc.ToString());
這是我的結果:
<ParentNode>
<ChildNode>This is an</ChildNode>
<ChildNode>example v</ChildNode>
<ChildNode>alue</ChildNode>
</ParentNode>
通過這種方式,您可以直接檢查從上一個子級剪切並附加到文檔的新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.