-->

Visio 2010 C# Entity Automation

2019-08-07 09:40发布

问题:

I apologize if this was asked before, but after searching for some time, I could not find any specific answer on this.

I have an ERD diagram in Visio 2010. It has around 15 tables or so. In order to have our DBAs create the database, I have to output each column to excel sheet with the data type, primary key, description.

My first attempt was to simply copy and paste the column definitions table from the shape properties, but this does not work (thanks Microsoft!). After trying a few other things, it turned out I would have to copy every cell manually for every table - time consuming.

I turned to C# and Visio Interop for help. I am able to export the column definitions now (they are in Text property of the shape), but I can not find the property which holds the name of the table.

Does anyone know which object holds this property, or if it is even accessible?

Thank you

回答1:

In the end I solved it. I was unable to parse out the standard Visio drawing (.vsd) so I opted for Visio XML Drawing (.vdx). In the end, this worked for me:

Where path is the file path to the vxd drawing. I turned out that each shape definition in the page in XML drawing has 2 shapes of its own. The first shape holds the Entity name, the second holds the Entity Columns.

XDocument xdoc = XDocument.Load(path);
var elements = xdoc.Elements().Elements();
XName pageXName = XName.Get("Page","http://schemas.microsoft.com/visio/2003/core");
var pages = elements.Elements(pageXName);

foreach (XElement page in pages)
{                
    XName shapeXName = XName.Get("Shape","http://schemas.microsoft.com/visio/2003/core");
    var shapes = from shape in page.Elements().Elements(shapeXName)
                 where shape.Attribute("Type").Value == "Group"
                 select shape;

    foreach (XElement shape in shapes)
    {
        var shapeShapes = shape.Elements();
        List<XElement> textShapes = shapeShapes.Elements(shapeXName).ToList();

        XName textXName = XName.Get("Text","http://schemas.microsoft.com/visio/2003/core");
        XName cpXName = XName.Get("Text", "http://schemas.microsoft.com/visio/2003/core");

        string tableName = textShapes[0].Elements(textXName).SingleOrDefault().Value;
        string columns = textShapes[1].Elements(textXName).SingleOrDefault().Value;

        Debug.WriteLine("-------------" + tableName.TrimEnd('\n') + "---------------");
        Debug.Write(columns);
        Debug.WriteLine("----------------------------");

    }
}