Search code examples
c#wpfxmlreader

What the method name of the XmlReader getting the current file path?


My application saves the content to the XML file or reads the content from the XML file. The content is project structure and the XML file can exist everywhere.

For example, the structure of the XML file my application using is as shown below.

<Project version="1">
    <Item Include="A.text"/>
    <Item Include="Folder/A.text"/>
</Project>

As you can see, the include tag of the Item is a relative path, therefore it needs a root path to open the item. (Project file path)

My application structure to process is as shown below.

public class Project, IXmlSerializable
{
    public ObservableCollection<Item> Items {get; set;} = new ObservableCollection<Item>();

    public XmlSchema GetSchema() => null;

    public void ReadXml(XmlReader reader)
    {
        // here would read ChildNode (Items)
    }

    public void WriteXml(XmlWriter writer)
    {
        ...
    }
}


public class Item, IXmlSerializable
{
    public XmlSchema GetSchema() => null;

    public void ReadXml(XmlReader reader)
    {
        ...
    }

    public void WriteXml(XmlWriter writer)
    {
        ...
    }
}

And reading code is as shown below.

using (StreamReader sr = new StreamReader(message.ProjectFullPath))
{
    XmlSerializer xs = new XmlSerializer(typeof(ProjectStruct));
    this.Projects.Add(xs.Deserialize(sr) as ProjectStruct);
}

As you can see, I created writing, reading logic deriving IXmlSerializable to use Serialize, DeSerialize function.

When the DeSerialize method is called, the ReadXml method of the ProjectStruct would be called. And ReadXml method has not parameter other than XmlReader so I can't pass ProjectFullPath to the ReadXML method.

Therefore I think need to get ProjectFullPath from XmlReader.

Could someone tell me what the method name of the XmlReader getting the current file path?

If you have another way to solve this problem please let me know. I don't obsess my way.

Thanks for reading.


Solution

  • You cannot pass anything else than the XmlReader that the interface defines to the ReadXml method.

    Depending on how you instantiate the Item class, you may be able to inject it with a string that defines the path:

    public class Item(string path)
    ...
    

    If you can't do this, you should include the full path in the XML data and read it from there.

    The last resort may be to get it from a static property of Item that you set before you begin to process the XML file.

    Anyway, you can't modify the signature of the method.