从XML文档中删除空行

时间:2011-12-14 09:41:54

标签: c# asp.net xml-parsing

我目前正面临一个问题。我在C#中加载一个xml文件,并从中删除一些节点并附加一些节点。现在的问题是,当我从xml文件中删除时,会自动创建一些空行,所以我想删除这些行。

当我将一些节点附加到xml中的父节点时,我想在每个结束标记中添加新行

对于Eg。我的Xml文件是

<intro id="S0001">
    <title>Introduction Title</title>
     <para>This is a paragraph. Note that paragraphs can contain other block–level objects, such as lists, as well as directly containing text.</para>
     <para>The introduction can contain all of the text objects that a section can contain, except that it cannot be divided into parts, sections and sub–sections.</para>
     <para>The introduction can contain tables:</para>

   </intro><part>
       <no>Part A</no> Article Structure <sup>&lpar;Part Title&rpar;</sup><section1 id="S0002">`enter code here`
     <no>Sect 1</no>
     <title>First Section in Part 1 <sup>&lpar;Section 1 Title&rpar;</sup></title>
     <shortsectionhead>Short Section Header</shortsectionhead>
     <para>This is a section in the first part of the article.</para>
   </section1><section1 id="S0003">

代码:

XmlNode partNnode = xmlDoc.SelectSingleNode("//part");
XmlNode introNode=xmlDoc.SelectSingleNode("//intro");
XmlDocumentFragment newNode=xmlDoc.CreateDocumentFragment();
newNode.InnerXml=partNnode.OuterXml;
introNode.ParentNode.InsertAfter(newNode,introNode);
partNnode.ParentNode.RemoveChild(partNnode);
partNnode = xmlDoc.SelectSingleNode("//part");
nodeList = xmlDoc.SelectNodes("//section1");    

foreach (XmlNode refrangeNode in nodeList)
{
    newNode=xmlDoc.CreateDocumentFragment();
    newNode.InnerXml=refrangeNode.??OuterXml;
    partNnode.AppendChild(newNode);
} 

请帮帮我 提前致谢

1 个答案:

答案 0 :(得分:0)

如果使用C#加载和保存XMl文件,那么XML的格式应该正确(格式化奇怪的XML文件的简单方法就是加载并用一些C#代码保存它们)。

如果我理解你的问题,那么你对XML文件的格式不满意吗?

就像你想要的那样(A):

</intro><part>

但你得到(B):

</intro>
<part>

如果这是个问题,那么,在我看来,你只想要一个奇怪的东西。因为...

a)代码不关心XML文件的格式和方式 b)(B)中的格式是正确的

如果您出于什么原因想要更改它,那么您必须解析XML文件,将其作为字符串打开并手动检查已关闭和打开的标记。