This tutorial shows how to load graph data from XML and create diagram objects corresponding to the graph nodes and edges.
Follow steps 1-5 from Tutorial 1: Getting started.
From the project's context menu choose Add -> New Item. Create a new XML file called SampleGraph.xml and add the following markup to its content.
XML Copy Code |
---|
<?xml version="1.0" encoding="utf-8" ?> |
Set the file's "Build Action" property to "Content" and "Copy to Output Directory" to "Copy if newer".
Open HomeController.cs file and and the following references
C# Copy Code |
---|
using Microsoft.AspNetCore.Hosting; |
We will get access to the SampleGraph.xml file, located in the wwwroot/js folder by injecting and querying the IHostingEnvironment service. Add a private variable
and a constructor method to the HomeController class as follows:
C# Copy Code |
---|
private readonly IHostingEnvironment env; public HomeController(IHostingEnvironment hostingEnvironment) |
Delete the code for creating nodes and links in the code block and add declarations for the following variables. "nodeMap" maps diagram nodes to their identifiers, and "bounds" contains the default node size.
C# Copy Code |
---|
Dictionary<string, DiagramNode> nodeMap = new Dictionary<string, DiagramNode>(); |
Load the XML document and its root element using the Linq for XML API:
C# Copy Code |
---|
var path = env.WebRootFileProvider.GetFileInfo("js//SampleGraph.xml")?.PhysicalPath; |
Load the graph node elements and create their corresponding ShapeNode objects by calling the CreateShapeNode method of the Factory class. CreateShapeNode is just a shortcut to creating a ShapeNode instance using the "new" operator and adding it to the Nodes collection of the diagram. Additionally, this code maps the new node to the "id" attribute of the XML element, and sets the node's Text to the value of the "name" attribute.
C# Copy Code |
---|
var nodes = xml.Descendants("Node"); |
Load the graph links and create corresponding DiagramLink objects. The Origin and Destination of the links are accessed by their ids through the "nodeMap" dictionary.
C# Copy Code |
---|
var links = xml.Descendants("Link"); |
Arrange the diagram using the LayeredLayout class. Call the Diagram's ResizeToFitItems method to ensure that its bounds will fit all diagram items.
C# Copy Code |
---|
var layout = new LayeredLayout(); |
Build and run the project. If everything is fine, you should see this representation of the graph: