NodeCollection

NodeCollection class

表示特定类型的节点集合。

要了解更多信息,请访问Aspose.Words 文档对象模型(DOM)文档文章。

public class NodeCollection : IEnumerable<Node>

特性

姓名描述
Count { get; }获取集合中的节点数。
Item { get; }检索给定索引处的节点。

方法

姓名描述
Add(Node)在集合末尾添加一个节点。
Clear()从此集合和文档中删除所有节点。
Contains(Node)确定节点是否在集合中。
GetEnumerator()提供对节点集合的简单“foreach”样式迭代。
IndexOf(Node)返回指定节点的从零开始的索引。
Insert(int, Node)将节点插入到指定索引的集合中。
Remove(Node)从集合和文档中删除节点。
RemoveAt(int)从集合和文档中删除指定索引处的节点。
ToArray()将集合中的所有节点复制到新的节点数组。

评论

NodeCollection并不拥有它所包含的节点,而只是指定类型的 nodes 的选择,但这些节点存储在它们各自的父节点下的树中。

NodeCollection支持索引访问、迭代并提供添加和删除方法。

NodeCollection集合是“实时的”,即对创建它的节点 object 的子节点的更改将立即反映在由NodeCollection 属性和方法。

NodeCollection返回的是GetChildNodes 也可作为类型节点集合的基类,例如SectionCollection, ParagraphCollection ETC。

NodeCollection可以是“平面的”并且仅包含创建它的节点的直属子节点,也可以是“深的”并且包含所有后代子节点。

例子

展示如何用图像形状替换所有文本框形状。

Document doc = new Document(MyDir + "Textboxes in drawing canvas.docx");

Shape[] shapes = doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>().ToArray();

Assert.AreEqual(3, shapes.Count(s => s.ShapeType == ShapeType.TextBox));
Assert.AreEqual(1, shapes.Count(s => s.ShapeType == ShapeType.Image));

foreach (Shape shape in shapes)
{
    if (shape.ShapeType == ShapeType.TextBox)
    {
        Shape replacementShape = new Shape(doc, ShapeType.Image);
        replacementShape.ImageData.SetImage(ImageDir + "Logo.jpg");
        replacementShape.Left = shape.Left;
        replacementShape.Top = shape.Top;
        replacementShape.Width = shape.Width;
        replacementShape.Height = shape.Height;
        replacementShape.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        replacementShape.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        replacementShape.HorizontalAlignment = shape.HorizontalAlignment;
        replacementShape.VerticalAlignment = shape.VerticalAlignment;
        replacementShape.WrapType = shape.WrapType;
        replacementShape.WrapSide = shape.WrapSide;

        shape.ParentNode.InsertAfter(replacementShape, shape);
        shape.Remove();
    }
}

shapes = doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>().ToArray();

Assert.AreEqual(0, shapes.Count(s => s.ShapeType == ShapeType.TextBox));
Assert.AreEqual(4, shapes.Count(s => s.ShapeType == ShapeType.Image));

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.docx");

也可以看看