0

我有一个如下的xml:-

<Comments>
    <Comment Text="ABC">
        <Note Timestamp="3/25/2013 8:26AM" Text="Movie">
    </Note>
</Comments>

我想在同一行结束评论标签,例如,

<Comment Text="ABC"/>

我已将字符串替换所有操作应用为:-

str.replaceAll("><Note", "/><Note");

但由于注释和注释标签之间的空格不定,它不起作用。请注意,空间每次都会有所不同。请建议我如何实现这一目标。

4

2 回答 2

0

这是您的解决方案,

in = in.replaceAll(">[\\s]*<Note", "/><Note");

于 2013-03-27T09:50:01.590 回答
0

You could do this using Linq by replacing each Note-node with a new one. Simplified example handling only the first node (tested in Linqpad):

 XElement oldStructure = 
     XElement.Parse(@"<Comment Text=""ABC"">
                       <Note Timestamp=""3/25/2013 8:26AM!"" Text=""Movie"">
                       </Note></Comment>");

 oldStructure.Dump("Original"); 

 // Replace this with some kind of lookup for each Note-element:
 var noteNode = (XElement) oldStructure.FirstNode; 

 // Create a new node. Note that it has no content:
 // (The null could be left out - left it here just to be explicit)
 var simplifiedNote = new XElement(noteNode.Name, null);
 noteNode.Attributes().ToList().ForEach(
    attrib => simplifiedNote.Add(new XAttribute(attrib.Name, attrib.Value)));

 // Replace with newly generated node - Linq will automatically use 
 // the compact format for you here, since the node has no content. 
 oldStructure.FirstNode.ReplaceWith(simplifiedNote);

 oldStructure.Dump("Final");

Running this in Linqpad will first dump the following:

Original:

<Comment Text="ABC">
   <Note Timestamp="3/25/2013 8:26AM!" Text="Movie"></Note>
</Comment>

Final:

<Comment Text="ABC">
   <Note Timestamp="3/25/2013 8:26AM!" Text="Movie" />
</Comment>
于 2013-03-27T10:59:19.537 回答