簡體   English   中英

最簡單的方式更改xml字符串

[英]Altering xml string the easiest way

我從外部來源獲取fetchXml,需要在其中插入屬性。 目前,我正在通過替換我肯定要添加的屬性來進行問答。

String fetchy = ...;
String surely = "<attribute name=\"entity_uno_id\" />";
String addity = "<attribute name=\"entity_duo_id\" />";
return fetchy.Replace(surely, surely + addity);

這很丑陋而且不專業。 我可以以更安全的方式重新設計它嗎? 我無法控制投放給我的fetchXml。

試試這個

 string xmlString = ... // the whole xml string;
    var xml = XElement.Parse(xmlString);
    var xElement = new XElement(XName.Get("attribute", null));
    xElement.SetAttributeValue(XName.Get("name", null), "entity_duo_id");
    xml.Add(xElement);

如果您可以控制接收的fetchXml,請讓他們以String.Format就緒類型的格式對其進行格式化。 例如,如果您當前的字符串如下所示:

var xml = "<blah><attribute name='entity_uno_id' /></blah>"

更改為此:

var xml = "<blah><attribute name='entity_uno_id' />{0}</blah>"

然后您可以添加任何您想要的內容:

String fetchy = ...;
String addity = "<attribute name='entity_duo_id' />";
return String.Format(fetchy, addity);

編輯1

假設您仍然可以控制獲取的xml,以便在xml的正確位置包含{0} ,則此擴展方法將起作用:

public static string AddAttributes(this string fetchXml, params string[] attributeNames)
{
    return String.Format(fetchXml, String.Join(String.Empty, attributeNames.Select(a => "<attribute name='" + a + "' />")));
}

暫無
暫無

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

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