简体   繁体   English

最简单的方式更改xml字符串

[英]Altering xml string the easiest way

I'm getting a fetchXml from an external source and I need to insert an attribute into it. 我从外部来源获取fetchXml,需要在其中插入属性。 At this moment I'm doing a Q&D by replacing an attribute that surely resides there by itself together with the one I'd like to add. 目前,我正在通过替换我肯定要添加的属性来进行问答。

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

This is ugly and not professional. 这很丑陋而且不专业。 Can I redesign it in a safer way? 我可以以更安全的方式重新设计它吗? I have no control over the fetchXml being served to me. 我无法控制投放给我的fetchXml。

Try something like this 试试这个

 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);

If you have control over the fetchXml that your receiving, have them format it in a String.Format ready type of formatting. 如果您可以控制接收的fetchXml,请让他们以String.Format就绪类型的格式对其进行格式化。 For example, if your current string looks like this: 例如,如果您当前的字符串如下所示:

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

change it to this: 更改为此:

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

then you can add whatever you want like this: 然后您可以添加任何您想要的内容:

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

EDIT 1 编辑1

Assuming you still have control over the fetch xml given to include the {0} in the correct location of the xml, this extension method would work: 假设您仍然可以控制获取的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