删除标记名称但保留其值

时间:2016-07-15 01:43:50

标签: c#

我需要删除标记名称,但保留其值或内容。我能够删除它的标签,但这也删除了它的内容或价值。

但我只需删除其标记名称及其属性,并保留其内容。我怎样才能做到这一点?

以下是示例xml文件:

<i><RefSource>1</RefSource></i>
<i><RefSource value="1">3</RefSource></i>

所需的输出:

<i>1</i>
<i>3</i>

xml文件的另一部分。因为xml文件有不同的标签  <Somename> <OrgDivision>Ask question</OrgDivision> <OrgName>Ask question organization</OrgName> <OrgAddress> <City>a</City> <State>b</State> <Country>c</Country> </OrgAddress> </Somename>

我想要的是删除OrgAddress

可能的输出

<Somename> <OrgDivision>Ask question</OrgDivision> <OrgName>Ask question organization</OrgName>  <City>a</City> <State>b</State> <Country>c</Country>  </Somename>

另一个问题。

我必须检查标签名称及其属性

<Emphasis Type="Italic">n</Emphasis>

如果我找到了一个带有Type =&#34; Italic&#34;的强调标签名称属性。将其标记名称更改为I

所需的输出是

<i>n<i>

代码尝试删除标记名称

XDocument doc = XDocument.Load("xmlfile.xml");


                    doc.Descendants("RefSource")
                        .Remove();

但它也删除了价值。我只需要删除标签名称

2 个答案:

答案 0 :(得分:1)

XDocument doc = XDocument.Load("xmlfile.xml");

// Remove RefSource tags.
foreach (var node in doc.Descendants("RefSource").ToList())
{
    node.ReplaceWith(node.Value);
}

// Remove OrgAddress tags.
foreach (var node in doc.Root.Descendants().ToList())
{
    if (node.HasElements)
    {
        node.ReplaceWith(node.Elements());
    }
}

// Change Emphasis tags to i tags.
foreach (var node in doc.Descendants("Emphasis").ToList())
{
    node.ReplaceWith(new XElement("i", node.Value));
}

doc.Save("xmlfile2.xml");

答案 1 :(得分:-1)

您是否尝试过使用正则表达式? XML文件是基于文本的文件。您可以使用Regex Replace进行所需的替换。 例如,

正则表达式 -

(?is)</?RefSource.*?>

替换字符串 - [空]

目标字符串 -

<i><RefSource>1</RefSource></i>

<i><RefSource value="1">3</RefSource></i>

您可以在http://regexhero.net/tester/

尝试

在替换之后,您可以将该文件与XMLDocument一起使用。